List of usage examples for java.sql ResultSet CONCUR_READ_ONLY
int CONCUR_READ_ONLY
To view the source code for java.sql ResultSet CONCUR_READ_ONLY.
Click Source Link
ResultSet
object that may NOT be updated. From source file:edu.ku.brc.af.core.db.MySQLBackupService.java
public int getNumberofTables() { Connection dbConnection = null; Statement dbStatement = null; try {/* w ww . j av a 2 s .c om*/ dbConnection = DBConnection.getInstance().createConnection(); if (dbConnection != null) { dbStatement = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet = dbStatement.executeQuery("SHOW TABLES"); ResultSetMetaData metaData = resultSet.getMetaData(); numTables = 0; while (resultSet.next()) { for (int i = 0; i < metaData.getColumnCount(); i++) { numTables++; } } resultSet.close(); return numTables; } } catch (SQLException ex) { ex.printStackTrace(); } finally { try { if (dbStatement != null) { dbStatement.close(); } if (dbConnection != null) { dbConnection.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } return -1; }
From source file:com.cloudera.sqoop.testutil.ExportJobTestCase.java
/** @return the minimum 'id' value in the table */ protected int getMinRowId(Connection conn) throws SQLException { PreparedStatement statement = conn.prepareStatement("SELECT MIN(id) FROM " + getTableName(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); int minVal = 0; try {//www. j a v a2s. co m ResultSet rs = statement.executeQuery(); try { rs.next(); minVal = rs.getInt(1); } finally { rs.close(); } } finally { statement.close(); } return minVal; }
From source file:net.mlw.vlh.adapter.jdbc.util.ConfigurableStatementBuilder.java
/** * @see net.mlw.vlh.adapter.jdbc.util.StatementBuilder#generate(java.sql.Connection, java.lang.StringBuffer, java.util.Map, boolean) *///from www.j a va2 s. c om public PreparedStatement generate(Connection conn, StringBuffer query, Map whereClause, boolean scrollable) throws SQLException, ParseException { if (!init) { init(); } if (whereClause == null) { whereClause = Collections.EMPTY_MAP; } for (Iterator iter = textManipulators.iterator(); iter.hasNext();) { TextManipulator manipulator = (TextManipulator) iter.next(); manipulator.manipulate(query, whereClause); } LinkedList arguments = new LinkedList(); // Replace any "{key}" with the value in the whereClause Map, // then placing the value in the partameters list. for (int i = 0, end = 0, start; ((start = query.toString().indexOf('{', end)) >= 0); i++) { end = query.toString().indexOf('}', start); String key = query.substring(start + 1, end); Object value = whereClause.get(key); if (value == null) { throw new NullPointerException("Property '" + key + "' was not provided."); } arguments.add(new NamedPair(key, value)); Setter setter = getSetter(key); query.replace(start, end + 1, setter.getReplacementString(value)); end -= (key.length() + 2); } PreparedStatement statement = null; if (scrollable) { statement = conn.prepareStatement(query.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } else { statement = conn.prepareStatement(query.toString()); } int index = 1; // Now set all the patameters on the statement. for (Iterator iter = arguments.iterator(); iter.hasNext();) { NamedPair namedPair = (NamedPair) iter.next(); Setter setter = getSetter(namedPair.getName()); try { index = setter.set(statement, index, namedPair.getValue()); } catch (RuntimeException e) { String message = "Cannot set value of " + namedPair.getName() + " (setter = " + setter + ")"; LOGGER.error(message, e); throw new RuntimeException(message, e); } } return statement; }
From source file:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java
private String getNameField(final Connection conn, final String table, final String db) throws BackendException { Statement st = null;/*from w ww. ja va2s . c o m*/ ResultSet rs = null; String result = null; try { String schema = this.getSchemaName(table, db); String plainTable = this.getPlainTableName(table); st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); StringBuilder sb = new StringBuilder(""); sb.append("select k.column_name "); sb.append(" from information_schema.table_constraints c "); sb.append(" inner join information_schema.key_column_usage k "); sb.append(" on c.constraint_catalog = k.constraint_catalog and "); sb.append(" c.constraint_schema = k.constraint_schema and "); sb.append(" c.constraint_name = k.constraint_name "); sb.append(" where c.constraint_type='PRIMARY KEY' and "); sb.append(" c.table_name='%s' and "); sb.append(" c.table_schema='%s'"); String queryString = String.format(sb.toString().replaceAll("[ ]+", " "), plainTable, schema); this.logString(queryString, "?"); rs = st.executeQuery(queryString); if (this.getNumRows(rs) != 1) { throw new BackendException( String.format("Table %s.%s has no or a multi column primary key which is not supported.", this.getSchemaName(table, db), this.getPlainTableName(table))); } rs.next(); result = rs.getString(1); } catch (SQLException e) { throw new BackendException(e); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(st); } return result; }
From source file:com.splicemachine.derby.impl.sql.execute.operations.CallStatementOperationIT.java
@Test public void testCallSQLTABLES() throws Exception { CallableStatement cs = methodWatcher.prepareCall( "call SYSIBM.SQLTABLES(null,'SYS',null,'SYSTEM TABLE',null)", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = cs.executeQuery(); int count = 0; while (rs.next()) { Object data = rs.getObject(2); count++;/* w w w . j av a2s . co m*/ } Assert.assertTrue("Incorrect rows returned!", count > 0); DbUtils.closeQuietly(rs); }
From source file:com.mongosqlmigrator.harsha.sql.DocBuilder.java
public Map<String, Object> getFields(Map<String, Object> firstRow, ResultSet rs, Entity entity, Map<String, Object> entityMap, Map<String, Object> rootEntityMap) throws SQLException { entityMap = new HashMap<String, Object>(); if (entity.allAttributes.get(MULTI_VALUED) != null && entity.allAttributes.get(MULTI_VALUED).equalsIgnoreCase("true")) { getMultiValuedEntity(rs, entity, rootEntityMap); } else if (firstRow != null) { getSingleValuedEntity(firstRow, rs, entity, entityMap); }// ww w. j a v a 2 s.co m if (entity.entities != null) { Entity subEntity = null; String query = "", aparam = ""; for (Iterator<Entity> iterator = entity.entities.iterator(); iterator.hasNext();) { subEntity = (Entity) iterator.next(); subLevel = subConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); query = subEntity.allAttributes.get("query"); m = p.matcher(query); aparam = ""; try { log.info("Parameter Map is: " + params); while (m.find()) { aparam = query.substring(m.start() + 2, m.end() - 1); query = query.replaceAll("(\\$\\{" + aparam + "\\})", Matcher.quoteReplacement(StringEscapeUtils.escapeSql(params.get(aparam)))); m = p.matcher(query); } } catch (Exception e) { e.printStackTrace(); } resultSet = subLevel.executeQuery(query); if (resultSet.next()) { subEntityData = getFields(processor.toMap(resultSet), resultSet, subEntity, null, entityMap); if (subEntityData.size() > 0) entityMap.put(subEntity.name, subEntityData); } resultSet.close(); subLevel.close(); } } return entityMap; }
From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java
public DBStore(BaseConnector connector) { Connection connection = null; logger = Logger.getLogger(this.getClass().getPackage().getName()); logger.log(Level.INFO, "Initialize DBStore "); this.connector = connector; //each connector instance has its own table in the same database this.instance_table = "i_" + connector.getInstanceName(); Statement Stmt = null;/*from www .j a va 2 s .c om*/ ResultSet RS = null; DatabaseMetaData dbm = null; boolean table_exists = false; try { //check if the datasource/database exists Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); ds = (DataSource) envCtx.lookup(BaseConstants.CONNECTOR_DATASOURCE); connection = ds.getConnection(); connection.setAutoCommit(true); dbm = connection.getMetaData(); logger.log(Level.INFO, "Connected to databaseType " + dbm.getDatabaseProductName()); } catch (Exception ex) { logger.log(Level.SEVERE, "Exception initializing Store Datasource " + ex); connection = null; return; } try { if (dbm.getDatabaseProductName().equals("MySQL")) { //check if the per-connector table exists logger.log(Level.FINE, "Checking to see if connector DB exists..."); Stmt = connection.createStatement(); RS = Stmt.executeQuery("desc " + instance_table); ResultSetMetaData rsMetaData = RS.getMetaData(); if (rsMetaData.getColumnCount() > 0) table_exists = true; RS.close(); Stmt.close(); } else { logger.log(Level.SEVERE, "Unsupported DATABASE TYPE..." + dbm.getDatabaseProductName()); } } catch (Exception ex) { logger.log(Level.SEVERE, "Exception initializing Store " + ex); } try { //if the per-instance table doesn't exist, create it if (!table_exists) { logger.log(Level.INFO, "Creating Instance Table " + instance_table); if (dbm.getDatabaseProductName().equals("MySQL")) { Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String create_stmt = ""; create_stmt = "CREATE TABLE `" + this.instance_table + "` (" + "`crawl_set` decimal(19,5) NOT NULL," + "`insert_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP," + "`crawl_data` MEDIUMTEXT default NULL," + "PRIMARY KEY (`crawl_set`)," + "KEY `set_index` (`crawl_set`)" + ") ENGINE=MyISAM;"; statement.addBatch(create_stmt); statement.executeBatch(); statement.close(); } else { logger.log(Level.INFO, "Instance Table " + instance_table + " already exists"); //connection.close(); //TODO: somehow figure out if we should delete this table here } } boolean qrtz_table_exists = false; if (dbm.getDatabaseProductName().equals("MySQL")) { //check if the per-connector table exists logger.log(Level.FINE, "Checking to see if quartz tables exists..."); Stmt = connection.createStatement(); try { RS = Stmt.executeQuery("desc QRTZ_JOB_DETAILS"); ResultSetMetaData rsMetaData = RS.getMetaData(); if (rsMetaData.getColumnCount() > 0) qrtz_table_exists = true; } catch (Exception ex) { logger.log(Level.INFO, "Could not find Quartz Tables...creating now.."); } RS.close(); Stmt.close(); } else { logger.log(Level.SEVERE, "Unsupported DATABASE TYPE..." + dbm.getDatabaseProductName()); } if (!qrtz_table_exists) { logger.log(Level.INFO, "Creating Global Quartz Table "); //the quartz db setup scripts are at //quartz-1.8.0/docs/dbTables/tables_mysql.sql //one set of Quartz tables can handle any number of triggers/crons Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String create_stmt = "CREATE TABLE QRTZ_JOB_DETAILS (JOB_NAME VARCHAR(200) NOT NULL,JOB_GROUP VARCHAR(200) NOT NULL,DESCRIPTION VARCHAR(250) NULL,JOB_CLASS_NAME VARCHAR(250) NOT NULL,IS_DURABLE VARCHAR(1) NOT NULL,IS_VOLATILE VARCHAR(1) NOT NULL,IS_STATEFUL VARCHAR(1) NOT NULL,REQUESTS_RECOVERY VARCHAR(1) NOT NULL,JOB_DATA BLOB NULL,PRIMARY KEY (JOB_NAME,JOB_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_JOB_LISTENERS ( JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, JOB_LISTENER VARCHAR(200) NOT NULL, PRIMARY KEY (JOB_NAME,JOB_GROUP,JOB_LISTENER), FOREIGN KEY (JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_FIRED_TRIGGERS ( ENTRY_ID VARCHAR(95) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, IS_VOLATILE VARCHAR(1) NOT NULL, INSTANCE_NAME VARCHAR(200) NOT NULL, FIRED_TIME BIGINT(13) NOT NULL, PRIORITY INTEGER NOT NULL, STATE VARCHAR(16) NOT NULL, JOB_NAME VARCHAR(200) NULL, JOB_GROUP VARCHAR(200) NULL, IS_STATEFUL VARCHAR(1) NULL, REQUESTS_RECOVERY VARCHAR(1) NULL, PRIMARY KEY (ENTRY_ID));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, IS_VOLATILE VARCHAR(1) NOT NULL, DESCRIPTION VARCHAR(250) NULL, NEXT_FIRE_TIME BIGINT(13) NULL, PREV_FIRE_TIME BIGINT(13) NULL, PRIORITY INTEGER NULL, TRIGGER_STATE VARCHAR(16) NOT NULL, TRIGGER_TYPE VARCHAR(8) NOT NULL, START_TIME BIGINT(13) NOT NULL, END_TIME BIGINT(13) NULL, CALENDAR_NAME VARCHAR(200) NULL, MISFIRE_INSTR SMALLINT(2) NULL, JOB_DATA BLOB NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_SIMPLE_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, REPEAT_COUNT BIGINT(7) NOT NULL, REPEAT_INTERVAL BIGINT(12) NOT NULL, TIMES_TRIGGERED BIGINT(10) NOT NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_CRON_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, CRON_EXPRESSION VARCHAR(200) NOT NULL, TIME_ZONE_ID VARCHAR(80), PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_BLOB_TRIGGERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, BLOB_DATA BLOB NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_TRIGGER_LISTENERS ( TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, TRIGGER_LISTENER VARCHAR(200) NOT NULL, PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_LISTENER), FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_CALENDARS ( CALENDAR_NAME VARCHAR(200) NOT NULL, CALENDAR BLOB NOT NULL, PRIMARY KEY (CALENDAR_NAME));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS ( TRIGGER_GROUP VARCHAR(200) NOT NULL, PRIMARY KEY (TRIGGER_GROUP));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_SCHEDULER_STATE ( INSTANCE_NAME VARCHAR(200) NOT NULL, LAST_CHECKIN_TIME BIGINT(13) NOT NULL, CHECKIN_INTERVAL BIGINT(13) NOT NULL, PRIMARY KEY (INSTANCE_NAME));"; statement.addBatch(create_stmt); create_stmt = "CREATE TABLE QRTZ_LOCKS ( LOCK_NAME VARCHAR(40) NOT NULL, PRIMARY KEY (LOCK_NAME));"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('TRIGGER_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('JOB_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('CALENDAR_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('STATE_ACCESS');"; statement.addBatch(create_stmt); create_stmt = "INSERT INTO QRTZ_LOCKS values('MISFIRE_ACCESS');"; statement.addBatch(create_stmt); statement.executeBatch(); statement.close(); } else { logger.log(Level.INFO, "Global Quartz Table already exists "); } connection.close(); } catch (Exception ex) { logger.log(Level.SEVERE, "Exception Creating StoreTable " + ex); } }
From source file:com.cloudera.sqoop.testutil.ExportJobTestCase.java
/** @return the maximum 'id' value in the table */ protected int getMaxRowId(Connection conn) throws SQLException { PreparedStatement statement = conn.prepareStatement("SELECT MAX(id) FROM " + getTableName(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); int maxVal = 0; try {/*w w w .j a va 2 s. co m*/ ResultSet rs = statement.executeQuery(); try { rs.next(); maxVal = rs.getInt(1); } finally { rs.close(); } } finally { statement.close(); } return maxVal; }
From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java
public String[] getUserList() { String[] userImeis = null;/* w ww. j ava 2s . c o m*/ List<String> tempResults = new ArrayList<String>(); PreparedStatement listUsersStmt = null; Connection conn = null; try { conn = getDbConnection(); listUsersStmt = conn.prepareStatement(SELECT_ALL_USERS_STATEMENT, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet surveysSet = listUsersStmt.executeQuery(); boolean isValidRow = surveysSet.first(); while (isValidRow) { tempResults.add(surveysSet.getString(IMEI_COLUMN)); isValidRow = surveysSet.next(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { listUsersStmt.close(); conn.close(); } catch (Exception e) { } } userImeis = tempResults.toArray(new String[tempResults.size()]); return userImeis; }
From source file:com.itemanalysis.jmetrik.stats.itemanalysis.ItemAnalysis.java
public void summarize() throws IllegalArgumentException, SQLException { Statement stmt = null;/* w w w. j a v a2s.com*/ ResultSet rs = null; int missingCount = 0; int numberOfSubscales = this.numberOfSubscales(); try { //connect to db Table sqlTable = new Table(tableName.getNameForDatabase()); SelectQuery select = new SelectQuery(); for (VariableAttributes v : variables) { select.addColumn(sqlTable, v.getName().nameForDatabase()); } stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(select.toString()); //create test summary object testSummary = new TestSummary(numberOfItems, numberOfSubscales, cutScores, variables, unbiased, deletedReliability, showCsem); Object response = null; Double responseScore = null; RawScore rawScore = null; ClassicalItem tempItem = null; int[] resposneVectorIndex = null; Object[] responseVector = null; Double[] scoreVector = null; //loop over examinees while (rs.next()) { //loop over items to compute RawScore rawScore = new RawScore(numberOfItems); missingCount = 0; for (VariableAttributes v : variables) { tempItem = item.get(v.positionInDb()); if (tempItem == null) { tempItem = new ClassicalItem(v, biasCorrection, allCategories, pearsonCorrelation, dIndex); item.put(v.positionInDb(), tempItem); } response = rs.getObject(v.getName().nameForDatabase()); //count missing responses per examinee if (response == null || response.equals("")) {//FIXME need to allow a space " " or other special codes to be viewed as missing data missingCount++; } responseScore = v.getItemScoring().computeItemScore(response); rawScore.increment(responseScore); rawScore.incrementResponseVector(v.positionInDb(), response, responseScore); rawScore.incrementSubScaleScore(v.getItemGroup(), responseScore); } //only use complete cases if listwise deletion is specified //otherwise a missing item response is scored as 0 if ((listwiseDeletion && missingCount == 0) || !listwiseDeletion) { // System.out.println("TEST: " + listwiseDeletion + " " + (missingCount==0) + " " + (listwiseDeletion && missingCount==0)); testSummary.increment(rawScore); if (numberOfSubscales > 1) testSummary.incrementPartTestReliability(rawScore); //loop over items to compute item analysis responseVector = rawScore.getResponseVector(); resposneVectorIndex = rawScore.getResponseVectorIndex(); scoreVector = rawScore.getScoreVector(); for (int i = 0; i < responseVector.length; i++) { if (showItemStats) { item.get(resposneVectorIndex[i]).increment(rawScore, responseVector[i]); } for (int j = i; j < responseVector.length; j++) { testSummary.incrementReliability(i, j, scoreVector[i], scoreVector[j]); } } } updateProgress(); } //end loop over examinees if (dIndex) { double[] bounds = testSummary.getDIndexBounds(); computeDindex(bounds[0], bounds[1]); } } catch (SQLException ex) { throw ex; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); conn.setAutoCommit(true); } }