Example usage for java.sql ResultSet getRow

List of usage examples for java.sql ResultSet getRow

Introduction

In this page you can find the example usage for java.sql ResultSet getRow.

Prototype

int getRow() throws SQLException;

Source Link

Document

Retrieves the current row number.

Usage

From source file:org.owasp.webgoat.plugin.CrossSiteScriptingLesson6a.java

protected AttackResult injectableQuery(String accountName) {
    try {//from  w w w . j  a v  a 2s  .  c o m
        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:org.jasig.schedassist.impl.owner.SpringJDBCPublicProfileDaoImpl.java

@Override
public Map<PublicProfileId, List<PublicProfileTag>> getProfileTagsBatch(List<PublicProfileId> profileIds) {
    // keep a map to quickly lookup profileId by key
    final Map<String, PublicProfileId> idMap = new HashMap<String, PublicProfileId>();

    final String sql = "select profile_key,tag,tag_display from profile_tags where profile_key in (:key)";

    for (PublicProfileId profileId : profileIds) {
        String key = profileId.getProfileKey();
        // populate idMap with key->profileId
        idMap.put(key, profileId);/*from ww  w  . j  a  v  a2 s .  c  o m*/
    }
    // map to name the parameters
    Map<String, Object> paramMap = new HashMap<String, Object>();
    List<String> keys = new ArrayList<String>(idMap.keySet());
    paramMap.put("key", keys);

    Map<PublicProfileId, List<PublicProfileTag>> results = this.namedParameterJdbcTemplate.query(sql.toString(),
            paramMap, new ResultSetExtractor<Map<PublicProfileId, List<PublicProfileTag>>>() {
                private final PublicProfileTagRowMapper TAG_ROW_MAPPER = new PublicProfileTagRowMapper();

                @Override
                public Map<PublicProfileId, List<PublicProfileTag>> extractData(ResultSet rs)
                        throws SQLException, DataAccessException {
                    Map<PublicProfileId, List<PublicProfileTag>> results = new HashMap<PublicProfileId, List<PublicProfileTag>>();
                    while (rs.next()) {
                        PublicProfileTag tag = TAG_ROW_MAPPER.mapRow(rs, rs.getRow());

                        PublicProfileId profileId = idMap.get(tag.getProfileKey());
                        List<PublicProfileTag> listForKey = results.get(profileId);
                        if (listForKey == null) {
                            listForKey = new ArrayList<PublicProfileTag>();
                            results.put(profileId, listForKey);
                        }
                        listForKey.add(tag);
                    }
                    return results;
                }
            });
    return results;
}

From source file:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java

private int getNumRows(final ResultSet rs) throws SQLException {
    if (!rs.last()) {
        return 0;
    }/*from w  ww . jav 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);/* w  ww  .  j  a v a 2  s  . c o 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:Connexion.ChartMutuelle.java

public ChartMutuelle() {

    try {/*from w w w.  j  a v  a  2s  . 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);
}

From source file:com.dianping.puma.parser.meta.DefaultTableMetaInfoFetcher.java

protected TableMetaInfo _refreshTableMeta(final String database, final String table) throws SQLException {
    initDsIfNeeded();//from  www  .j  a  va  2  s  . c  om

    QueryRunner runner = new QueryRunner(metaDs);

    Transaction t = Cat.newTransaction("SQL.meta", getKey(database, table));
    try {
        TableMetaInfo tableMetaInfo = runner.query(genTableMetaSql(database, table),
                new ResultSetHandler<TableMetaInfo>() {
                    @Override
                    public TableMetaInfo handle(ResultSet rs) throws SQLException {
                        TableMetaInfo result = new TableMetaInfo();
                        result.setDatabase(database);
                        result.setTable(table);
                        result.setColumns(new HashMap<Integer, String>());
                        result.setKeys(new ArrayList<String>());
                        result.setTypes(new HashMap<String, String>());
                        result.setSignedInfos(new HashMap<Integer, Boolean>());

                        while (rs.next()) {
                            int i = rs.getRow();
                            String column = rs.getString("Field");

                            result.getColumns().put(i, column);

                            if (rs.getString("Type").contains("unsigned")) {
                                result.getSignedInfos().put(i, false);
                            } else {
                                result.getSignedInfos().put(i, true);
                            }

                            if (rs.getString("Key").equalsIgnoreCase("pri")) {
                                result.getKeys().add(column);
                            }
                        }

                        return result;
                    }
                });

        t.setStatus("0");
        return tableMetaInfo;
    } catch (SQLException e) {
        t.setStatus("1");
        throw e;
    } finally {
        t.complete();
    }
}

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  www. ja v  a  2  s . 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:com.graphaware.importer.data.access.QueueDbDataReader.java

/**
 * {@inheritDoc}/*from   ww w  .  jav a  2 s .  c  o m*/
 */
@Override
public final void read(final String query, final String hint) {
    if (records != null) {
        throw new IllegalStateException("Previous reader hasn't been closed");
    }

    LOG.info("Start query: \n" + query);

    if (query.startsWith("alter")) {
        jdbcTemplate.execute(query);
        noMoreRecords = true;
        return;
    }

    records = new ArrayBlockingQueue<>(queueCapacity());

    new Thread(new Runnable() {
        @Override
        public void run() {
            Date d1 = Calendar.getInstance().getTime();

            try {
                jdbcTemplate.query(query, new ResultSetExtractor<Void>() {
                    @Override
                    public Void extractData(ResultSet rs) throws SQLException, DataAccessException {
                        ResultSetMetaData metaData = rs.getMetaData();
                        int colCount = metaData.getColumnCount();

                        while (rs.next()) {
                            Map<String, String> columns = new HashMap<>();
                            for (int i = 1; i <= colCount; i++) {
                                columns.put(metaData.getColumnLabel(i), rs.getString(i));
                            }
                            columns.put(ROW, String.valueOf(rs.getRow()));

                            try {
                                records.offer(columns, 1, TimeUnit.HOURS);
                            } catch (InterruptedException e) {
                                LOG.warn(
                                        "Was waiting for more than 1 hour to insert a record for processing, had to drop it");
                            }
                        }

                        return null;
                    }
                });
            } finally {
                noMoreRecords = true;
            }

            long diffInSeconds = TimeUnit.MILLISECONDS
                    .toSeconds(Calendar.getInstance().getTime().getTime() - d1.getTime());

            LOG.info("Finished querying for " + hint + " in " + diffInSeconds + " seconds");
        }
    }, "DB READER - " + hint).start();
}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

/**
 * Verify that the driver navigates a resultset according to the JDBC rules.
 * In all cases, the resultset should be pointing to the first record, which can
 * be read without invoking {@code next()}.
 * @throws Exception  Fatal error.//  www  . ja  v  a2  s. c  o m
 */
@Test
public void testResultSetNavigation() throws Exception {
    Statement statement = con.createStatement();

    String truncate = "TRUNCATE regressiontest;";
    statement.execute(truncate);

    String insert1 = "INSERT INTO regressiontest (keyname,bValue,iValue) VALUES( 'key0',true, 2000);";
    statement.executeUpdate(insert1);

    String insert2 = "INSERT INTO regressiontest (keyname,bValue) VALUES( 'key1',false);";
    statement.executeUpdate(insert2);

    String select = "SELECT * from regressiontest;";

    ResultSet result = statement.executeQuery(select);

    ResultSetMetaData metadata = result.getMetaData();

    int colCount = metadata.getColumnCount();

    System.out.println("Before doing a next()");
    System.out.printf("(%d) ", result.getRow());
    for (int i = 1; i <= colCount; i++) {
        System.out.print(showColumn(i, result) + " ");
    }
    System.out.println();

    System.out.println("Fetching each row with a next()");
    while (result.next()) {
        metadata = result.getMetaData();
        colCount = metadata.getColumnCount();
        System.out.printf("(%d) ", result.getRow());
        for (int i = 1; i <= colCount; i++) {
            System.out.print(showColumn(i, result) + " ");
        }
        System.out.println();
    }
}

From source file:SyncMusicServlet.java

private void processSongData(String androidId, String title, String album, String artist, String genre) {
    Connection conn = null;// w ww  . j a va 2  s . co m
    Statement stmt = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {

        Class.forName(JDBC_DRIVER);
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        // Get the albumId
        String sql = "select album_id from album where album_title='" + album + "'";
        rs = stmt.executeQuery(sql);
        rs.next();
        int albumId = rs.getInt("album_id");

        sql = "select * from song where song_title = '" + title.replaceAll("'", "\u0027") + "'";
        rs = stmt.executeQuery(sql);
        rs.next();
        if (rs.getRow() == 0) {

            // Insert Song
            pstmt = conn.prepareStatement(
                    "insert into song (song_title, genre, artist_name, album_id) values (?, ?, ?, ?)");
            pstmt.setString(1, title.replaceAll("'", "\u0027"));
            pstmt.setString(2, genre);
            pstmt.setString(3, artist);
            pstmt.setInt(4, albumId);
            pstmt.executeUpdate();
        }

        // Get Song Id
        sql = "select song_id from song where song_title='" + title.replaceAll("'", "\u0027") + "'";
        rs = stmt.executeQuery(sql);
        rs.next();
        int songId = rs.getInt("song_id");

        // Check if user_music_data entry exist
        sql = "select * from user_music_data where song_id=" + songId + " AND android_id='" + androidId + "'";
        rs = stmt.executeQuery(sql);
        rs.next();
        if (rs.getRow() == 0) {
            // Insert into user_music_data
            sql = "insert into user_music_data (android_id, song_id) values ('" + androidId + "', " + songId
                    + ")";
            stmt.executeUpdate(sql);
        }
        //out.print(resultJSON);
    } catch (Exception se) {
        //out.println("Exception preparing or processing query: " + se);
        se.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {

        }
    }
}