List of usage examples for java.sql ResultSet TYPE_SCROLL_INSENSITIVE
int TYPE_SCROLL_INSENSITIVE
To view the source code for java.sql ResultSet TYPE_SCROLL_INSENSITIVE.
Click Source Link
ResultSet
object that is scrollable but generally not sensitive to changes to the data that underlies the ResultSet
. From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java
/** * Deletes all the records from a table//from w w w. j a va 2 s . c om * @param connection connection to the DB * @param tableName the name of the table * @return the return value from the SQL update statement (or -1 on an exception) */ public static int deleteAllRecordsFromTable(final Connection connection, final String tableName, final SERVERTYPE currentServerType) { try { if (doesTableExist(connection, tableName)) { Integer count = getCount(connection, "SELECT COUNT(*) FROM " + tableName); if (count == null || count == 0) { return 0; } Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); if (currentServerType != SERVERTYPE.MS_SQLServer) { removeForeignKeyConstraints(stmt.getConnection(), currentServerType); } int retVal = exeUpdateCmd(stmt, "delete from " + tableName); stmt.clearBatch(); stmt.close(); log.info("Deleted " + count + " records from " + tableName); return retVal; } } catch (SQLException ex) { edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BasicSQLUtils.class, ex); log.error(ex); ex.printStackTrace(); } return 0; }
From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.JdbcCrawler.java
/** * Populates the {@link #_groupingRanges}-{@link ArrayList} according to the configuration specified in the * {@link Grouping}-attribute of the {@link DataSourceConnectionConfig}. The SQL-statements needed for this are * executed via a local {@link Statement}-object, just as the data is retrieved via a local {@link ResultSet}-object. * //from w w w . j a v a2s . co m * @throws CrawlerCriticalException * If any of the following conditions occur: * <ul> * <li>Any of the columns used for grouping has a data type which is not supported: !(Number||String)</li> * <li>A SQLException is raised while retrieving the grouping data from the database</li> * </ul> */ private void prepareGrouping() throws CrawlerCriticalException { final Grouping grouping = _process.getSelections().getGrouping(); BigInteger stepping = BigInteger.ONE; ResultSet groupingResultSet = null; ResultSetMetaData groupingMetaData = null; if (grouping != null) { _groupingRanges = new ArrayList<GroupingRange>(); final String groupingSQL = grouping.getSQL(); stepping = grouping.getStepping(); Statement groupingStatement = null; try { groupingStatement = _connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); _log.debug("Executing SQL for grouping preparation: [" + groupingSQL + "]"); groupingResultSet = groupingStatement.executeQuery(groupingSQL); groupingMetaData = groupingResultSet.getMetaData(); _log.debug("Retrieved groupingResultSet with [" + groupingMetaData.getColumnCount() + "] columns"); for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) { Class<?> columnClass = null; try { columnClass = Class.forName(groupingMetaData.getColumnClassName(i)); } catch (final ClassNotFoundException e) { _log.error("This should never happen: the class[" + groupingMetaData.getColumnClassName(i) + "] for the column " + i + " in the grouping result set could not be resolved"); } if (Number.class.isAssignableFrom(columnClass)) { _log.debug("RowNr " + i + " of the grouping result set is of type [" + columnClass.getName() + "], which is derived from [Number]: fine for use in a grouping"); continue; } else if (String.class.equals(columnClass)) { _log.debug("RowNr " + i + " of the grouping result set is of type [String]: fine for use in a grouping"); } else { throw new CrawlerCriticalException("RowNr " + i + " of the grouping result set is of type [" + columnClass.getName() + "]: NOT supported as a grouping field"); } } int groupingRecords = 0; PreparedStatementTypedParameter[] startValues = null; PreparedStatementTypedParameter[] endValues = null; final PreparedStatementTypedParameter[] finalValues = new PreparedStatementTypedParameter[groupingMetaData .getColumnCount()]; while (groupingResultSet.next()) { if (groupingRecords == 0) { startValues = new PreparedStatementTypedParameter[groupingMetaData.getColumnCount()]; for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) { startValues[i - 1] = new PreparedStatementTypedParameter(groupingResultSet.getObject(i), (i * 2) - 1, groupingMetaData.getColumnType(i)); } } groupingRecords++; if (groupingRecords == stepping.intValue()) { endValues = new PreparedStatementTypedParameter[groupingMetaData.getColumnCount()]; for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) { endValues[i - 1] = new PreparedStatementTypedParameter(groupingResultSet.getObject(i), i * 2, groupingMetaData.getColumnType(i)); } final GroupingRange groupingRange = new GroupingRange(startValues, endValues); _groupingRanges.add(groupingRange); if (_log.isTraceEnabled()) { _log.trace( "Added GroupingRange: [" + groupingRange.toString() + "] to _groupingRanges"); } groupingRecords = 0; continue; } for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) { finalValues[i - 1] = new PreparedStatementTypedParameter(groupingResultSet.getObject(i), i * 2, groupingMetaData.getColumnType(i)); } } if (groupingRecords != 0 && stepping.intValue() != 1) { final GroupingRange finalgroupingRange = new GroupingRange(startValues, finalValues); _groupingRanges.add(finalgroupingRange); _log.debug( "Added final GroupingRange [" + finalgroupingRange.toString() + "] to _groupingRanges"); } } catch (final SQLException e1) { throw new CrawlerCriticalException("Encountered SQLException while preparing Groupings"); } finally { try { if (groupingStatement != null) { groupingStatement.close(); } } catch (final SQLException e) { _log.error("Could not closeGrouping statement"); } try { groupingResultSet.close(); _log.debug("Closed Grouping Resultset"); } catch (final SQLException e) { _log.error("Could not close Resultset for Grouping statement"); } } } // set current grouping to first grouping in list (if list is not empty) _groupingRangesIterator = _groupingRanges.iterator(); if (_groupingRangesIterator.hasNext()) { _currentGroupingRange = _groupingRangesIterator.next(); } _log.debug(String.format("Prepared %d grouping ranges based on specified stepping of %d", _groupingRanges.size(), stepping.intValue())); }
From source file:net.starschema.clouddb.jdbc.ScrollableResultset.java
/** * <p>// w w w .j a v a 2 s .c om * <h1>Implementation Details:</h1><br> * Always returns ResultSet.TYPE_SCROLL_INSENSITIVE * </p> * * @return ResultSet.TYPE_SCROLL_INSENSITIVE */ @Override public int getType() throws SQLException { if (this.isClosed()) { throw new BQSQLException("This Resultset is Closed"); } return ResultSet.TYPE_SCROLL_INSENSITIVE; }
From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java
/** * Removes all the records from all the tables *//* w ww . j a v a2s . c om*/ public static void cleanAllTables(final Connection connection, SERVERTYPE currentServerType) { try { Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("show tables"); if (rs.first()) { do { String tableName = rs.getString(1); //System.out.println("Deleting Records from "+tableName); deleteAllRecordsFromTable(connection, tableName, currentServerType); } while (rs.next()); } rs.close(); stmt.clearBatch(); stmt.close(); } catch (SQLException ex) { edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BasicSQLUtils.class, ex); log.error(ex); ex.printStackTrace(); } }
From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCLogsDAO.java
public List<Activity> getLogs(String resourcePath, int action, String userName, Date from, Date to, boolean descending) throws RepositoryException { JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection(); try {// w w w. j a v a 2 s . c om String dbName = conn.getMetaData().getDatabaseProductName(); if (dbName.contains("Microsoft") || dbName.equals("Oracle")) { enableApiPagination = "false"; } } catch (SQLException e) { throw new RepositoryDBException("Failed to get Database product name ", e); } if (conn == null) { log.fatal( "Failed to get Logs. Communications link failure. The connection to the database could not be acquired."); throw new RepositoryDBException( "Failed to get Logs. Communications link failure. The connection to the database could not be acquired."); } PreparedStatement s = null; ResultSet results = null; boolean paginated = false; int start = 0; int count = 0; String sortOrder = ""; String sortBy = ""; /* MessageContext messageContext = null; // enableApiPagination is the value of system property - enable.registry.api.paginating if (enableApiPagination == null || enableApiPagination.equals("true")) { messageContext = MessageContext.getCurrentMessageContext(); if (messageContext != null && PaginationUtils.isPaginationHeadersExist(messageContext)) { PaginationContext paginationContext = PaginationUtils.initPaginationContext(messageContext); start = paginationContext.getStart(); count = paginationContext.getCount(); if(start == 0){ start =1; } sortBy = paginationContext.getSortBy(); sortOrder = paginationContext.getSortOrder(); paginated = true; } } */ String sql = "SELECT REG_PATH, REG_USER_ID, REG_LOGGED_TIME, REG_ACTION, REG_ACTION_DATA FROM REG_LOG"; boolean queryStarted = false; sql = addWherePart(resourcePath, queryStarted, sql, userName, from, to, action); if (descending) { sql = sql + " ORDER BY REG_LOGGED_TIME DESC"; } try { if (enableApiPagination == null || enableApiPagination.equals("true")) { s = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); } else { s = conn.prepareStatement(sql); } int paramNumber = 1; if (resourcePath != null) { s.setString(paramNumber, resourcePath); paramNumber++; } if (userName != null) { s.setString(paramNumber, userName); paramNumber++; } if (from != null) { s.setTimestamp(paramNumber, new Timestamp(from.getTime())); paramNumber++; } if (to != null) { s.setTimestamp(paramNumber, new Timestamp(to.getTime())); paramNumber++; } if (action != -1) { s.setInt(paramNumber, action); paramNumber++; } s.setInt(paramNumber, CurrentContext.getTenantId()); results = s.executeQuery(); List<Activity> resultList = new ArrayList<Activity>(); if (paginated) { //Check start index is a valid one if (results.relative(start)) { //This is to get cursor to correct position to execute results.next(). results.previous(); int i = 0; while (results.next() && i < count) { i++; resultList.add(getLogEntry(results)); } } else { log.debug("start index doesn't exist in the result set"); } //move the cursor to the last index if (results.last()) { log.debug("cursor move to the last index of result set"); } else { log.debug("cursor doesn't move to the last index of result set"); } //set row count to the message context. // PaginationUtils.setRowCount(messageContext, Integer.toString(results.getRow())); } else { while (results.next()) { resultList.add(getLogEntry(results)); } // Activity[] logEntries = getPaginatedLogs(resultList.toArray(new Activity[resultList.size()])); // resultList = Arrays.asList(logEntries); } return resultList; } catch (SQLException e) { String msg = "Failed to get logs. " + e.getMessage(); log.error(msg, e); throw new RepositoryDBException(msg, e); } finally { try { try { if (results != null) { results.close(); } } finally { if (s != null) { s.close(); } } } catch (SQLException ex) { String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR; log.error(msg, ex); } } }
From source file:org.freebxml.omar.server.persistence.rdb.SQLPersistenceManagerImpl.java
/** * Executes an SQL Query.// w w w . ja va 2s. c o m */ public List executeSQLQuery(ServerRequestContext context, String sqlQuery, List queryParams, ResponseOptionType responseOption, String tableName, List objectRefs, IterativeQueryParams paramHolder) throws RegistryException { List res = null; Connection connection = null; int startIndex = paramHolder.startIndex; int maxResults = paramHolder.maxResults; int totalResultCount = -1; Statement stmt = null; try { connection = context.getConnection(); java.sql.ResultSet rs = null; tableName = org.freebxml.omar.common.Utility.getInstance().mapTableName(tableName); ReturnType returnType = responseOption.getReturnType(); boolean returnComposedObjects = responseOption.isReturnComposedObjects(); if (maxResults < 0) { if (queryParams == null) { stmt = connection.createStatement(); } else { stmt = connection.prepareStatement(sqlQuery); } } else { if (queryParams == null) { stmt = connection.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY); } else { stmt = connection.prepareStatement(sqlQuery, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY); } } if (log.isDebugEnabled()) { log.debug("Executing query: '" + sqlQuery + "'"); if (dumpStackOnQuery) { Thread.currentThread().dumpStack(); } } log.trace("SQL = " + sqlQuery); // HIEOS/BHT: (DEBUG) if (queryParams == null) { rs = stmt.executeQuery(sqlQuery); } else { Iterator iter = queryParams.iterator(); int paramCount = 0; while (iter.hasNext()) { Object param = iter.next(); ((PreparedStatement) stmt).setObject(++paramCount, param); // HIEOS/BHT (DEBUG): log.trace(" -> param(" + new Integer(paramCount).toString() + "): " + (String) param); } rs = ((PreparedStatement) stmt).executeQuery(); } if (maxResults >= 0) { rs.last(); totalResultCount = rs.getRow(); // Reset back to before first row so that DAO can correctly scroll // through the result set rs.beforeFirst(); } java.util.Iterator iter = null; if (returnType == ReturnType.OBJECT_REF) { res = new java.util.ArrayList(); if (startIndex > 0) { rs.last(); totalResultCount = rs.getRow(); rs.beforeFirst(); // calling rs.next() is a workaround for some drivers, such // as Derby's, that do not set the cursor during call to // rs.relative(...) rs.next(); boolean onRow = rs.relative(startIndex - 1); // HIEOS/BHT (DEBUG): log.trace(" -> Total Result Count: " + totalResultCount); } int cnt = 0; while (rs.next()) { org.oasis.ebxml.registry.bindings.rim.ObjectRef or = bu.rimFac.createObjectRef(); String id = rs.getString(1); or.setId(id); res.add(or); if (++cnt == maxResults) { break; } } // HIEOS/BHT (DEBUG): log.trace(" -> cnt: " + totalResultCount); } else if (returnType == ReturnType.REGISTRY_OBJECT) { context.setResponseOption(responseOption); RegistryObjectDAO roDAO = new RegistryObjectDAO(context); res = roDAO.getObjects(rs, startIndex, maxResults); // HIEOS/BHT (DEBUG): log.trace(" -> Object Size: " + res.size()); } else if ((returnType == ReturnType.LEAF_CLASS) || (returnType == ReturnType.LEAF_CLASS_WITH_REPOSITORY_ITEM)) { res = getObjects(context, connection, rs, tableName, responseOption, objectRefs, startIndex, maxResults); // HIEOS/BHT (DEBUG): log.trace(" -> Object Size: " + res.size()); } else { throw new RegistryException(ServerResourceBundle.getInstance() .getString("message.invalidReturnType", new Object[] { returnType })); } } catch (SQLException e) { throw new RegistryException(e); } catch (javax.xml.bind.JAXBException e) { throw new RegistryException(e); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException sqle) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), sqle); } } paramHolder.totalResultCount = totalResultCount; return res; }
From source file:org.xenei.jdbc4sparql.J4SDatabaseMetaData.java
@Override public boolean supportsResultSetType(final int arg0) throws SQLException { switch (arg0) { case ResultSet.TYPE_FORWARD_ONLY: case ResultSet.CONCUR_READ_ONLY: case ResultSet.TYPE_SCROLL_INSENSITIVE: case ResultSet.HOLD_CURSORS_OVER_COMMIT: return true; case ResultSet.CLOSE_CURSORS_AT_COMMIT: case ResultSet.CONCUR_UPDATABLE: case ResultSet.TYPE_SCROLL_SENSITIVE: default:/* w ww .j av a2s . co m*/ return false; } }
From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.JdbcCrawler.java
/** * This method is called during initialization and assembles the {@link PreparedStatement}-member * {@link #_retrievalStatement} used for data retrieval according to the configuration in the {@link Selections} * -attribute of the {@link DataSourceConnectionConfig}. If grouping is enabled in the * {@link DataSourceConnectionConfig} the {@link #prepareGrouping()}-method is called. * //from w ww. java 2 s . co m * @throws CrawlerCriticalException * If the {@link PreparedStatement} could not be created on the {@link #_connection} * */ private void prepareRetrievalStatement() throws CrawlerCriticalException { String retrievalSql = _process.getSelections().getSQL(); retrievalSql = retrievalSql.trim(); if (_process.getSelections().getGrouping() != null) { prepareGrouping(); _log.debug("Transforming SQL passed from index: [" + retrievalSql + "]"); final Pattern groupingPlaceholderPattern = Pattern.compile("%\\d\\d(min|max)"); final Matcher matcher = groupingPlaceholderPattern.matcher(retrievalSql); final String transformedSQL = matcher.replaceAll("?"); _log.debug("Using transformed SQL for PreparedStatement: [" + transformedSQL + "]"); retrievalSql = transformedSQL; } try { _retrievalStatement = _connection.prepareStatement(retrievalSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } catch (final SQLException e) { throw new CrawlerCriticalException("Failed to create statement on database connection", e); } }
From source file:org.apache.hive.jdbc.HiveConnection.java
@Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) { throw new SQLException( "Statement with resultset concurrency " + resultSetConcurrency + " is not supported", "HYC00"); // Optional feature not implemented }//from w w w.j a v a 2 s.c o m if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE) { throw new SQLException("Statement with resultset type " + resultSetType + " is not supported", "HYC00"); // Optional feature not implemented } return new HiveStatement(this, client, sessHandle, resultSetType == ResultSet.TYPE_SCROLL_INSENSITIVE, fetchSize); }