List of usage examples for java.sql ResultSet last
boolean last() throws SQLException;
ResultSet
object. From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBConnector.java
/** Checks if name='value' exists in the given table. If it does, returns its id. If not * inserts it into the table and returns the generated id. Works only for tables that * generate IDs, only for VARCHAR values, and only for tables that have only two columns: * ID and some VARCHAR column (given by name) */ public int insertIfDNE(String table, String name, String value) { Connection conn = null;// www. j a va 2 s . c om Object[] results = null; try { conn = getConnection(); String query = "select id from " + table + " where " + name + "='" + value + "'"; results = executeQuery(query, conn); int id = -1; //Check if name=value is there -- if so, return its id if (results != null) { ResultSet rs = (ResultSet) results[0]; if (!rs.wasNull()) { rs.last(); int size = rs.getRow(); if (size > 0) { id = rs.getInt("id"); return id; } } } //If the security was not found then add it and return the generated id String update = "insert into " + table + " values(0, '" + value + "')"; results = executeUpdate(update, conn); ResultSet rs = (ResultSet) results[0]; rs.next(); id = rs.getInt(1); return id; } catch (SQLException e) { log.error("Failed to perform a 'add if does not exist' table insert: " + e); return -1; } finally { closeQuery(results, conn); } }
From source file:Connexion.ChartDocteur.java
public ChartDocteur() { try {//w ww .ja v a 2 s. c o m Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { /* Grer les ventuelles erreurs ici. */ } int a = 0; int b = 0; int c = 0; int d = 0; int f = 0; int g = 0; try { ResultSet resultat1 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT specialite FROM docteur WHERE specialite = 'Cardiologue'"); // on rcupre le nombre de lignes de la requte if (resultat1.last()) { a = resultat1.getRow(); } System.out.println(a); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat2 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT specialite FROM docteur WHERE specialite = 'Traumatologue'"); // on rcupre le nombre de lignes de la requte if (resultat2.last()) { b = resultat2.getRow(); } System.out.println(b); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat3 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT specialite FROM docteur WHERE specialite = 'Pneumologue'"); // on rcupre le nombre de lignes de la requte if (resultat3.last()) { c = resultat3.getRow(); } System.out.println(c); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat4 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT specialite FROM docteur WHERE specialite = 'Orthopediste'"); // on rcupre le nombre de lignes de la requte if (resultat4.last()) { d = resultat4.getRow(); } System.out.println(d); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat5 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT specialite FROM docteur WHERE specialite = 'Radiologue'"); // on rcupre le nombre de lignes de la requte if (resultat5.last()) { f = resultat5.getRow(); } System.out.println(f); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat6 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT specialite FROM docteur WHERE specialite = 'Anesthesiste'"); // on rcupre le nombre de lignes de la requte if (resultat6.last()) { g = resultat6.getRow(); } System.out.println(g); } catch (SQLException e) { e.printStackTrace(); } DefaultPieDataset union = new DefaultPieDataset(); //remplir l'ensemble union.setValue("Cardiologue", a); union.setValue("Traumatologue", b); union.setValue("Pneumologue", c); union.setValue("Orthopediste", d); union.setValue("Radiologue", f); union.setValue("Anesthesiste", g); JFreeChart repart = ChartFactory.createPieChart3D("Nombre de mdecin par spcialit", union, true, true, false); ChartPanel crepart = new ChartPanel(repart); this.add(crepart); this.pack(); this.setVisible(true); }
From source file:org.syncope.core.init.ContentLoader.java
@Transactional public void load() { // 0. DB connection, to be used below Connection conn = DataSourceUtils.getConnection(dataSource); // 1. Check wether we are allowed to load default content into the DB Statement statement = null;//from ww w . j a va 2 s . c o m ResultSet resultSet = null; boolean existingData = false; try { statement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); resultSet = statement.executeQuery("SELECT * FROM " + SyncopeConf.class.getSimpleName()); resultSet.last(); existingData = resultSet.getRow() > 0; } catch (SQLException e) { LOG.error("Could not access to table " + SyncopeConf.class.getSimpleName(), e); // Setting this to true make nothing to be done below existingData = true; } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException e) { LOG.error("While closing SQL result set", e); } try { if (statement != null) { statement.close(); } } catch (SQLException e) { LOG.error("While closing SQL statement", e); } } if (existingData) { LOG.info("Data found in the database, leaving untouched"); return; } LOG.info("Empty database found, loading default content"); // 2. Create views LOG.debug("Creating views"); try { InputStream viewsStream = getClass().getResourceAsStream("/views.xml"); Properties views = new Properties(); views.loadFromXML(viewsStream); for (String idx : views.stringPropertyNames()) { LOG.debug("Creating view {}", views.get(idx).toString()); try { statement = conn.createStatement(); statement.executeUpdate(views.get(idx).toString().replaceAll("\\n", " ")); statement.close(); } catch (SQLException e) { LOG.error("Could not create view ", e); } } LOG.debug("Views created, go for indexes"); } catch (Throwable t) { LOG.error("While creating views", t); } // 3. Create indexes LOG.debug("Creating indexes"); try { InputStream indexesStream = getClass().getResourceAsStream("/indexes.xml"); Properties indexes = new Properties(); indexes.loadFromXML(indexesStream); for (String idx : indexes.stringPropertyNames()) { LOG.debug("Creating index {}", indexes.get(idx).toString()); try { statement = conn.createStatement(); statement.executeUpdate(indexes.get(idx).toString()); statement.close(); } catch (SQLException e) { LOG.error("Could not create index ", e); } } LOG.debug("Indexes created, go for default content"); } catch (Throwable t) { LOG.error("While creating indexes", t); } finally { DataSourceUtils.releaseConnection(conn, dataSource); } try { conn.close(); } catch (SQLException e) { LOG.error("While closing SQL connection", e); } // 4. Load default content SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); parser.parse(getClass().getResourceAsStream("/content.xml"), importExport); LOG.debug("Default content successfully loaded"); } catch (Throwable t) { LOG.error("While loading default content", t); } }
From source file:org.owasp.webgoat.plugin.CrossSiteScriptingLesson5b.java
protected AttackResult injectableQuery(String accountName) { try {//from w w w . ja va 2s. c om Connection connection = DatabaseUtilities.getConnection(getWebSession()); String query = "SELECT * FROM user_data WHERE userid = " + accountName; try { Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet results = statement.executeQuery(query); if ((results != null) && (results.first() == true)) { ResultSetMetaData resultsMetaData = results.getMetaData(); StringBuffer output = new StringBuffer(); output.append(writeTable(results, resultsMetaData)); results.last(); // If they get back more than one user they succeeded if (results.getRow() >= 6) { return trackProgress(AttackResult.success("You have succeed: " + output.toString())); } else { return trackProgress(AttackResult.failed("You are close, try again. " + output.toString())); } } else { return trackProgress(AttackResult.failed("No Results Matched. Try Again. ")); // output.append(getLabelManager().get("NoResultsMatched")); } } catch (SQLException sqle) { return trackProgress(AttackResult.failed(sqle.getMessage())); } } catch (Exception e) { e.printStackTrace(); return trackProgress( AttackResult.failed("ErrorGenerating" + this.getClass().getName() + " : " + e.getMessage())); } }
From source file:org.owasp.webgoat.plugin.CrossSiteScriptingLesson6a.java
protected AttackResult injectableQuery(String accountName) { try {//from w w w. j av a2 s. com Connection connection = DatabaseUtilities.getConnection(getWebSession()); String query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'"; try { Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet results = statement.executeQuery(query); if ((results != null) && (results.first() == true)) { ResultSetMetaData resultsMetaData = results.getMetaData(); StringBuffer output = new StringBuffer(); output.append(writeTable(results, resultsMetaData)); results.last(); // If they get back more than one user they succeeded if (results.getRow() >= 6) { return trackProgress(AttackResult.success("You have succeed: " + output.toString())); } else { return trackProgress(AttackResult.failed("You are close, try again. " + output.toString())); } } else { return trackProgress(AttackResult.failed("No Results Matched. Try Again. ")); } } catch (SQLException sqle) { return trackProgress(AttackResult.failed(sqle.getMessage())); } } catch (Exception e) { e.printStackTrace(); return trackProgress( AttackResult.failed("ErrorGenerating" + this.getClass().getName() + " : " + e.getMessage())); } }
From source file:hmp.HMPReadFilterer.java
private void createDBStructure(String runDate, String tag, int region, TagCollection tags, PrintWriter debug) throws SQLException { System.out.println("\tChecking DB Structure"); Statement s = conn.createStatement(); ResultSet rs; if (!runInDB) { rs = s.executeQuery("select * from run where date ='" + runDate + "'"); rs.last(); int rowCount = rs.getRow(); rs.beforeFirst();//from w ww.j a va2 s . c o m if (rowCount == 0) { System.out.println("rowCount == 0"); createRunInDatabase(s, runDate); } else { runInDB = true; } } if (!sampleInDB && runInDB) { String sample = tags.getSampleForTagFromRegion(region, tag); rs = s.executeQuery("select * from sample where sample_name ='" + sample + "'"); rs.last(); int rowCount = rs.getRow(); rs.beforeFirst(); if (rowCount == 0) { createSampleForRunInDatabase(s, runDate, tag, sample, region, debug); } else { deleteSampleDataFromDatabase(sample); } } else { sampleInDB = true; } }
From source file:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java
private int getNumRows(final ResultSet rs) throws SQLException { if (!rs.last()) { return 0; }/* ww w . ja v a 2s. c o m*/ int result = rs.getRow(); rs.beforeFirst(); return result; }
From source file:Data.java
private JTable getTbleData(Statement stmt) throws SQLException, ClassNotFoundException { ResultSet rs; String sql = "SELECT pro_name, pro_description, COUNT(sto_uid) - (SUM(sto_inout) * 2) AS NbProduit FROM t_produit, t_stock WHERE t_produit.id_produit = t_stock.id_produit GROUP BY t_produit.id_produit"; rs = stmt.executeQuery(sql);/*www .jav a 2 s.co m*/ rs.last(); Object rowData[][] = new Object[rs.getRow()][3]; rs.beforeFirst(); while (rs.next()) { rowData[rs.getRow() - 1][0] = rs.getString(1); rowData[rs.getRow() - 1][1] = rs.getString(2); rowData[rs.getRow() - 1][2] = rs.getInt(3); } sql = "SELECT tmp_temperature, tmp_humidity FROM t_temphum ORDER BY tmp_date DESC LIMIT 1"; rs = stmt.executeQuery(sql); rs.first(); if (tempUnit == "C") { tempRealTime.setText("Temprature : " + rs.getDouble(1) + "" + tempUnit); } else { tempRealTime.setText("Temprature : " + celsiusToFahrenheit(rs.getString(1)) + "" + tempUnit); } humRealTime.setText("Humidit : " + rs.getDouble(2) + "%"); lastTemp = rs.getDouble(1); lastHum = rs.getDouble(2); Object columnNames[] = { "Poduit", "Description", "Quantit" }; JTable table = new JTable(rowData, columnNames); return table; }
From source file:edu.ku.brc.specify.conversion.IdHashMapper.java
/** * Maps the first index to the second index. * The SQL to do the mappings./*from w w w. j av a 2s . c o m*/ */ public void mapAllIds() { if (sql == null) { throw new RuntimeException("Calling mapAllIds and the SQL statement is NULL!"); } int mappingCount = getMapCount(mapTableName); wasEmpty = mappingCount == 0; if (doDelete || mappingCount == 0) { if (!isUsingSQL) { BasicSQLUtils.deleteAllRecordsFromTable(oldConn, mapTableName, BasicSQLUtils.myDestinationServerType); } if (frame != null) { frame.setDesc("Mapping " + mapTableName); } try { if (frame != null) { frame.setProcess(0, 0); } PreparedStatement pStmt = oldConn.prepareStatement("INSERT INTO " + mapTableName + " VALUES (?,?)"); Statement stmtOld = oldConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmtOld.executeQuery(sql); if (rs.last()) { if (frame != null) { frame.setProcess(0, rs.getRow()); } } if (rs.first()) { int count = 0; do { pStmt.setInt(1, rs.getInt(1)); // Old Index pStmt.setInt(2, rs.getInt(2)); // New Index if (pStmt.executeUpdate() != 1) { String msg = String.format("Error writing to Map table[%s] old: %d new: %d", mapTableName, rs.getInt(1), rs.getInt(2)); log.error(msg); throw new RuntimeException(msg); } if (frame != null) { if (count % 1000 == 0) { frame.setProcess(count); } } else { if (count % 2000 == 0) { log.debug("Mapped " + count + " records from " + tableName); } } count++; } while (rs.next()); log.info("Mapped " + count + " records from " + tableName); if (frame != null) { frame.setProcess(0, 0); } } else { log.info("No records to map in " + tableName); } rs.close(); stmtOld.close(); pStmt.close(); } catch (SQLException ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(IdHashMapper.class, ex); log.error("trying to execute:" + sql); log.error(ex); throw new RuntimeException(ex); } } else { log.debug("Skipping the build of mapper: " + mapTableName); } if (frame != null) { frame.setProcess(0, 0); } }
From source file:Connexion.ChartMutuelle.java
public ChartMutuelle() { try {/*from w w w.j av a 2 s .c o m*/ Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { /* Grer les ventuelles erreurs ici. */ } int ag2r = 0; int ccvrp = 0; int cnamts = 0; int lmde = 0; int maaf = 0; int mas = 0; int mgen = 0; int mgsp = 0; int mma = 0; int mnam = 0; int mnftc = 0; int mnh = 0; try { ResultSet resultat1 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'AG2R'"); // on rcupre le nombre de lignes de la requte if (resultat1.last()) { ag2r = resultat1.getRow(); } System.out.println(ag2r); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat2 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'CCVRP'"); // on rcupre le nombre de lignes de la requte if (resultat2.last()) { ccvrp = resultat2.getRow(); } System.out.println(ccvrp); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat3 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'CNAMTS'"); // on rcupre le nombre de lignes de la requte if (resultat3.last()) { cnamts = resultat3.getRow(); } System.out.println(cnamts); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat4 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'LMDE'"); // on rcupre le nombre de lignes de la requte if (resultat4.last()) { lmde = resultat4.getRow(); } System.out.println(lmde); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat5 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'MAAF'"); // on rcupre le nombre de lignes de la requte if (resultat5.last()) { maaf = resultat5.getRow(); } System.out.println(maaf); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat6 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'MAS'"); // on rcupre le nombre de lignes de la requte if (resultat6.last()) { mas = resultat6.getRow(); } System.out.println(mas); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat7 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'MGEN'"); // on rcupre le nombre de lignes de la requte if (resultat7.last()) { mgen = resultat7.getRow(); } System.out.println(mgen); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat8 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'MGSP'"); // on rcupre le nombre de lignes de la requte if (resultat8.last()) { mgsp = resultat8.getRow(); } System.out.println(mgsp); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat9 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'MMA'"); // on rcupre le nombre de lignes de la requte if (resultat9.last()) { mma = resultat9.getRow(); } System.out.println(mma); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat10 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'MNAM'"); // on rcupre le nombre de lignes de la requte if (resultat10.last()) { mnam = resultat10.getRow(); } System.out.println(mnam); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat11 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'MNFTC'"); // on rcupre le nombre de lignes de la requte if (resultat11.last()) { mnftc = resultat11.getRow(); } System.out.println(mnftc); } catch (SQLException e) { e.printStackTrace(); } try { ResultSet resultat12 = this.connect .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) .executeQuery("SELECT mutuelle FROM malade WHERE mutuelle = 'MNH'"); // on rcupre le nombre de lignes de la requte if (resultat12.last()) { mnh = resultat12.getRow(); } System.out.println(mnh); } catch (SQLException e) { e.printStackTrace(); } DefaultPieDataset union = new DefaultPieDataset(); //remplir l'ensemble union.setValue("AG2R", ag2r); union.setValue("CCVRP", ccvrp); union.setValue("CNAMTS", cnamts); union.setValue("LMDE", lmde); union.setValue("MAAD", maaf); union.setValue("MAS", mas); union.setValue("MGEN", mgen); union.setValue("MGSP", mgsp); union.setValue("MMA", mma); union.setValue("MNAM", mnam); union.setValue("MNFTC", mnftc); union.setValue("MNH", mnh); JFreeChart repart = ChartFactory.createPieChart3D("Nombre de malades par mutuelle", union, true, true, false); ChartPanel crepart = new ChartPanel(repart); this.add(crepart); this.pack(); this.setVisible(true); }