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: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 www . j a v a2 s.c om*/ 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.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); }/*from ww w .j a v a2 s. c o 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:org.owasp.webgoat.lessons.MaliciousFileExecution.java
/** * Description of the Method//from ww w .j a v a 2s . c o m * * @param s * Description of the Parameter * @return Description of the Return Value */ protected Element createContent(WebSession s) { if (uploads_and_target_parent_directory == null) { fill_uploads_and_target_parent_directory(s); } ElementContainer ec = new ElementContainer(); try { // check for success - see if the target file exists yet File userfile = new File(uploads_and_target_parent_directory + TARGET_RELATIVE_PATH + java.io.File.separator + s.getUserName() + ".txt"); if (userfile.exists()) { makeSuccess(s); } Connection connection = DatabaseUtilities.getConnection(s); ec.addElement(new H1().addElement("WebGoat Image Storage")); // show the current image ec.addElement(new P().addElement("Your current image:")); String image_query = "SELECT image_relative_url FROM mfe_images WHERE user_name = '" + s.getUserName() + "'"; Statement image_statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet image_results = image_statement.executeQuery(image_query); if (image_results.next() == false) { // result set was empty ec.addElement(new P().addElement("No image uploaded")); System.out.println("No image uploaded"); } else { String image_url = image_results.getString(1); ec.addElement(new IMG(image_url).setBorder(0).setHspace(0).setVspace(0)); System.out.println("Found image named: " + image_url); } ec.addElement(new P().addElement("Upload a new image:")); Input input = new Input(Input.FILE, "myfile", ""); ec.addElement(input); Element b = ECSFactory.makeButton("Start Upload"); ec.addElement(b); } catch (Exception e) { s.setMessage("Error generating " + this.getClass().getName()); e.printStackTrace(); } return (ec); }
From source file:orange.save.export.sql.DocBuilder.java
public Map<String, Object> getFields(Map<String, Object> firstRow, ResultSet resultSet, 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(resultSet, entity, rootEntityMap); } else if (firstRow != null) { getSingleValuedEntity(firstRow, resultSet, entity, entityMap); }//from w w w. j ava 2 s .com if (entity.entities != null) { Entity subEntity = null; String query = ""; String 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"); matcher = pattern.matcher(query); aparam = ""; try { log.info("Parameter Map is: " + params); while (matcher.find()) { aparam = query.substring(matcher.start() + 2, matcher.end() - 1); query = query.replaceAll("(\\$\\{" + aparam + "\\})", Matcher.quoteReplacement(StringEscapeUtils.escapeSql(params.get(aparam)))); matcher = pattern.matcher(query); } } catch (Exception e) { e.printStackTrace(); } this.resultSet = subLevel.executeQuery(query); if (this.resultSet.next()) { subEntityData = getFields(processor.toMap(this.resultSet), this.resultSet, subEntity, null, entityMap); if (subEntityData.size() > 0) entityMap.put(subEntity.name, subEntityData); } this.resultSet.close(); subLevel.close(); } } return entityMap; }
From source file:com.taobao.datax.plugins.writer.oraclejdbcwriter.OracleJdbcWriter.java
@Override public int startWrite(LineReceiver receiver) { PreparedStatement ps = null;//from w w w . ja v a 2 s . c o m try { this.connection = DBSource.getConnection(this.sourceUniqKey); this.logger.info(String.format("Config encoding %s .", this.encoding)); /* load data begin */ Line line = null; int lines = 0; if (StringUtils.isEmpty(this.insert)) { this.insert = this.buildInsertString(); } logger.debug("sql=" + insert); ps = this.connection.prepareStatement(this.insert, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.connection.setAutoCommit(false); while ((line = receiver.getFromReader()) != null) { try { for (int i = 0; i < line.getFieldNum(); i++) { ps.setObject(i + 1, line.getField(i)); } ps.execute(); } catch (SQLException e) { if (e.getMessage().contains("ORA-00001")) {// unique // constraint // violated logger.debug("Duplicated line found:" + line); duplicatedLineBuffer.add(line); if (this.duplicatedLineBuffer.size() >= this.duplicatedThreshold) { logger.info("Too much duplicated lines,now process them ."); this.connection.commit(); this.flushDuplicatedBuffer(); } } else { failCount++; logger.debug("Fail line(" + e.getMessage() + "):" + line); if (failCount >= this.limit) { throw new DataExchangeException("Too many failed lines(" + failCount + ") ."); } else { continue; } } } if (lines++ == this.commitCount) { logger.info(lines + " committed by worker " + Thread.currentThread().getName() + " ."); lines = 0; this.connection.commit(); } } this.connection.commit(); if (!this.duplicatedLineBuffer.isEmpty()) { logger.info("Some duplicated line will now be processed."); this.flushDuplicatedBuffer(); } this.connection.setAutoCommit(true); this.getMonitor().setFailedLines(this.failCount); this.logger.info("DataX write to oracle ends by worker " + Thread.currentThread().getName() + " ."); return PluginStatus.SUCCESS.value(); } catch (Exception e2) { e2.printStackTrace(); if (null != this.connection) { try { this.connection.close(); } catch (SQLException e) { } } throw new DataExchangeException(e2.getCause()); } finally { if (null != ps) try { ps.close(); } catch (SQLException e3) { } } }
From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java
public String[] getUserList() { String[] userImeis = null;/* ww w.j a v a 2s . co 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 ww . ja va2 s .co m*/ 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); } }
From source file:com.bc.fiduceo.db.AbstractDriver.java
Sensor getSensor(int id) throws SQLException { final Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); final ResultSet resultSet = statement.executeQuery("SELECT * FROM SENSOR where ID = " + id); if (resultSet.next()) { final Sensor sensor = new Sensor(); sensor.setName(resultSet.getString("Name")); return sensor; } else {/* ww w.j a v a 2s . c o m*/ throw new SQLException("No Sensor available for ID '" + id + "'"); } }
From source file:de.tudarmstadt.ukp.dkpro.core.io.jdbc.JdbcReader.java
private void query() throws ResourceInitializationException { try {/*from w w w . j a v a2s . c o m*/ Statement statement = sqlConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); resultSet = statement.executeQuery(query); resultSet.last(); resultSetSize = resultSet.getRow(); resultSet.beforeFirst(); completed = 0; // Store available column names columnNames = new HashSet<String>(); ResultSetMetaData meta = resultSet.getMetaData(); for (int i = 1; i < meta.getColumnCount() + 1; i++) { String columnName = meta.getColumnLabel(i); columnNames.add(columnName); if (!CAS_COLUMNS.contains(columnName)) { getLogger().warn("Unknown column [" + columnName + "]."); } } } catch (SQLException e) { throw new ResourceInitializationException(e); } }
From source file:com.itemanalysis.jmetrik.stats.transformation.LinearTransformationAnalysis.java
public String transformScore() throws SQLException { Statement stmt = null;/* www.j a v a2 s. c om*/ ResultSet rs = null; Double constrainedScore = null; try { //add variable to db dao.addColumnToDb(conn, tableName, addedVariableInfo); conn.setAutoCommit(false);//begin transaction Table sqlTable = new Table(tableName.getNameForDatabase()); SelectQuery select = new SelectQuery(); select.addColumn(sqlTable, selectedVariable.getName().nameForDatabase()); select.addColumn(sqlTable, addedVariableInfo.getName().nameForDatabase()); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(select.toString()); this.firePropertyChange("message", "", "Transforming scores..."); double origValue = 0.0; double transValue = 0.0; double z = 0.0; StandardDeviation sd = new StandardDeviation(); Mean mean = new Mean(); Min min = new Min(); Max max = new Max(); while (rs.next()) { origValue = rs.getDouble(selectedVariable.getName().nameForDatabase()); if (!rs.wasNull()) { sd.increment(origValue); mean.increment(origValue); min.increment(origValue); max.increment(origValue); } updateProgress(); } double meanValue = mean.getResult(); double sdValue = sd.getResult(); double minValue = min.getResult(); double maxValue = max.getResult(); double A = 1.0; double B = 0.0; rs.beforeFirst(); while (rs.next()) { origValue = rs.getDouble(selectedVariable.getName().nameForDatabase()); if (!rs.wasNull()) { if (type1) { z = (origValue - meanValue) / sdValue; transValue = scaleSd * z + scaleMean; transValue = checkConstraints(transValue); } else { A = (maxPossibleScore - minPossibleScore) / (maxValue - minValue); B = minPossibleScore - minValue * A; transValue = origValue * A + B; transValue = checkConstraints(transValue); } descriptiveStatistics.increment(transValue); rs.updateDouble(addedVariableInfo.getName().nameForDatabase(), transValue); rs.updateRow(); } updateProgress(); } conn.commit(); conn.setAutoCommit(true); //create output DefaultLinearTransformation linearTransformation = new DefaultLinearTransformation(); linearTransformation.setScale(A); linearTransformation.setIntercept(B); StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); f.format(publishHeader()); f.format(descriptiveStatistics.toString()); f.format(linearTransformation.toString()); f.format("%n"); f.format("%n"); return f.toString(); } catch (SQLException ex) { conn.rollback(); conn.setAutoCommit(true); throw ex; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } }