Example usage for java.sql ResultSet last

List of usage examples for java.sql ResultSet last

Introduction

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

Prototype

boolean last() throws SQLException;

Source Link

Document

Moves the cursor to the last row in this ResultSet object.

Usage

From source file:jmdbtools.JMdbTools.java

private void createTables(DbSchema schema, Connection conn) throws SQLException {

    Statement stmt = conn.createStatement();
    for (DbTable dbTable : schema.getTables()) {
        String createTableSql = new CreateTableQuery(dbTable, true).validate().toString();

        //TODO: DANGEROUS: auto override tables. Add explicit option to enable
        if (dbOverwrite) {
            log("Dropping existing table", "warn");
            stmt.executeUpdate("DROP TABLE IF EXISTS `" + dbTable.getName() + "`");
            log("creating table:" + dbTable.getName(), "info");
            stmt.executeUpdate(createTableSql);
        } else {//from w  ww .  ja  va 2 s  . c  o  m
            DatabaseMetaData meta = conn.getMetaData();
            ResultSet res = meta.getTables(null, null, dbTable.getName(), new String[] { "TABLE" });
            if (res.last()) {
                //there are entries for "TABLE" with this name don't try to create table
                log("Table already exists:" + dbTable.getName(), "info");

            } else {
                log("creating table:" + dbTable.getName(), "info");
                stmt.executeUpdate(createTableSql);
            }
        }
    }
}

From source file:com.vigglet.util.ModelUtilBase.java

public List<T> getLimitedList(int company, int limit) {
    long startMs = System.currentTimeMillis();
    logger.log(Level.INFO, "Fetching limited (" + limit + ") list...");
    List<T> result = null;/*w ww .j  a  va  2  s .  com*/

    try {
        PreparedStatement stmt = getLimitedQuery();
        stmt.setInt(1, company);
        stmt.setInt(2, limit);
        ResultSet rs = stmt.executeQuery();

        rs.last();
        result = new ArrayList<>(rs.getRow());
        rs.beforeFirst();

        while (rs.next()) {
            result.add(readModel(rs));
        }

        rs.close();
        stmt.close();

    } catch (SQLException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    long endMs = System.currentTimeMillis();
    logger.log(Level.INFO, "Done in " + (endMs - startMs) + " ms (" + (endMs - startMs) / 1000 + " s)");
    return result;
}

From source file:com.vigglet.util.ModelUtilBase.java

public List<T> getOrderdList(int company, String orderField, String orderDirection) {
    List<T> result = null;/*from w w  w. j  a  va 2s .  co  m*/

    try {
        PreparedStatement stmt = null;
        if (orderDirection != null && orderDirection.length() > 0) {
            stmt = getOrderByQuery(orderField, orderDirection);
        } else {
            stmt = getOrderByQuery(orderField);
        }
        stmt.setInt(1, company);
        ResultSet rs = stmt.executeQuery();

        rs.last();
        result = new ArrayList<>(rs.getRow());
        rs.beforeFirst();

        while (rs.next()) {
            result.add(readModel(rs));
        }

        rs.close();
        stmt.close();

    } catch (SQLException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:Connexion.Charts.java

public Charts() {

    try {//from ww w .ja v a2  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;
    try {
        ResultSet resultat1 = this.connect
                .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)
                .executeQuery("SELECT code_service FROM hospitalisation WHERE code_service =  'REA'");
        // 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 code_service FROM hospitalisation WHERE code_service =  'CHG'");
        // 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 code_service FROM hospitalisation WHERE code_service =  'CAR'");
        // on rcupre le nombre de lignes de la requte
        if (resultat3.last()) {
            c = resultat3.getRow();
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }

    DefaultPieDataset union = new DefaultPieDataset();

    //remplir l'ensemble

    union.setValue("REA", a);
    union.setValue("CAR", b);
    union.setValue("CHG", c);

    JFreeChart repart = ChartFactory.createPieChart3D("Nombre d'hospitalisation par service", union, true, true,
            false);
    ChartPanel crepart = new ChartPanel(repart);
    this.add(crepart);
    this.pack();
    this.setVisible(true);
}

From source file:org.owasp.webgoat.plugin.introduction.SqlInjectionLesson6a.java

protected AttackResult injectableQuery(String accountName) {
    try {//from w  w  w .jav  a  2 s . c om
        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())) {
                ResultSetMetaData resultsMetaData = results.getMetaData();
                StringBuffer output = new StringBuffer();

                output.append(SqlInjectionLesson5a.writeTable(results, resultsMetaData));
                results.last();

                // If they get back more than one user they succeeded
                if (results.getRow() >= 5) {
                    return trackProgress(success().feedback("sql-injection.6a.success")
                            .feedbackArgs(output.toString()).build());
                } else {
                    return trackProgress(failed().output(output.toString()).build());
                }

            } else {
                return trackProgress(failed().feedback("sql-injection.6a.no.results").build());

            }
        } catch (SQLException sqle) {
            return trackProgress(failed().output(sqle.getMessage()).build());
        }
    } catch (Exception e) {
        e.printStackTrace();
        return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage()).build());
    }
}

From source file:org.owasp.webgoat.plugin.introduction.SqlInjectionLesson5a.java

protected AttackResult injectableQuery(String accountName) {
    try {/*from  w w  w. j av a2 s  .  c om*/
        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())) {
                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(success().feedback("sql-injection.5a.success")
                            .feedbackArgs(output.toString()).build());
                } else {
                    return trackProgress(failed().output(output.toString()).build());
                }
            } else {
                return trackProgress(failed().feedback("sql-injection.5a.no.results").build());

            }
        } catch (SQLException sqle) {

            return trackProgress(failed().output(sqle.getMessage()).build());
        }
    } catch (Exception e) {
        return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage()).build());
    }
}

From source file:edu.ku.brc.specify.conversion.IdTableMapper.java

/**
 * Map all the old IDs to new IDs// ww w  .j  a  v a 2s .c  o  m
 * @param sqlArg the string to use to fill the map
 */
public void mapAllIdsNoIncrement(final String sqlArg, final Integer numRecords) {
    log.debug("mapAllIdsNoIncrement with sql: " + sqlArg);
    this.sql = sqlArg;

    int mappingCount = numRecords != null ? numRecords : getMapCount(mapTableName);
    wasEmpty = mappingCount == 0;

    if (doDelete || mappingCount == 0) {
        BasicSQLUtils.deleteAllRecordsFromTable(oldConn, mapTableName, BasicSQLUtils.myDestinationServerType);
        if (frame != null) {
            String dMsg = "Mapping " + mapTableName;
            frame.setDesc(dMsg);
            log.debug(dMsg);
        }

        try {
            log.debug("Executing: " + sql);
            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());
                }
            }

            int cnt = 0;
            if (rs.first()) {
                do {
                    int oldIndex = rs.getInt(1);
                    int toIndex = rs.getInt(2);
                    pStmt.setInt(1, oldIndex); // Old Index
                    pStmt.setInt(2, toIndex); // New Index
                    if (pStmt.executeUpdate() != 1) {
                        String msg = String.format("Error writing to Map table[%s] old: %d  new: %d",
                                mapTableName, oldIndex, toIndex);
                        log.error(msg);
                        throw new RuntimeException(msg);
                    }

                    if (frame != null) {
                        if (cnt % 1000 == 0) {
                            frame.setProcess(cnt);
                        }

                    } else {
                        if (cnt % 2000 == 0) {
                            log.debug("Mapped " + cnt + " records from " + tableName);
                        }
                    }

                    cnt++;

                } while (rs.next());

                log.info("Mapped " + cnt + " records from " + tableName);

            } 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(IdTableMapper.class, ex);
            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:org.owasp.webgoat.plugin.introduction.SqlInjectionLesson5b.java

protected AttackResult injectableQuery(String accountName) {
    try {/*from ww w . java  2  s. c o m*/
        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(SqlInjectionLesson5a.writeTable(results, resultsMetaData));
                results.last();

                // If they get back more than one user they succeeded
                if (results.getRow() >= 6) {
                    return trackProgress(success().feedback("sql-injection.5b.success")
                            .feedbackArgs(output.toString()).build());
                } else {
                    return trackProgress(failed().output(output.toString()).build());
                }

            } else {
                return trackProgress(failed().feedback("sql-injection.5b.no.results").build());

                //                    output.append(getLabelManager().get("NoResultsMatched"));
            }
        } catch (SQLException sqle) {

            return trackProgress(failed().output(sqle.getMessage()).build());
        }
    } catch (Exception e) {
        e.printStackTrace();
        return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage()).build());
    }
}

From source file:edu.ku.brc.specify.conversion.IdTableMapper.java

/**
 * Map all the old IDs to new IDs//from   w ww.j ava2  s.c o  m
 * @param sqlArg the string to use to fill the map
 */
public void mapAllIds(final String sqlArg) {
    log.debug("mapAllIds with sql: " + sqlArg);
    this.sql = sqlArg;

    int mappingCount = getMapCount(mapTableName);
    wasEmpty = mappingCount == 0;

    if (doDelete || mappingCount == 0) {
        BasicSQLUtils.deleteAllRecordsFromTable(oldConn, mapTableName, BasicSQLUtils.myDestinationServerType);
        if (frame != null) {
            String dMsg = "Mapping " + mapTableName;
            frame.setDesc(dMsg);
            log.debug(dMsg);
        }

        try {
            log.debug("Executing: " + sql);
            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 newIndex = initialIndex;
                do {
                    int oldIndex = rs.getInt(1);
                    //log.debug("map "+mapTableName+" old[" + oldIndex + "] new [" + newIndex +"]");

                    if (indexIncremeter != null) {
                        newIndex = indexIncremeter.getNextIndex();
                    }

                    pStmt.setInt(1, oldIndex); // Old Index
                    pStmt.setInt(2, newIndex); // New Index
                    if (pStmt.executeUpdate() != 1) {
                        String msg = String.format("Error writing to Map table[%s] old: %d  new: %d",
                                mapTableName, oldIndex, newIndex);
                        log.error(msg);
                        throw new RuntimeException(msg);
                    }

                    newIndex++; // incrementing doesn't matter when there is an indexIncremeter

                    if (frame != null) {
                        if (newIndex % 1000 == 0) {
                            frame.setProcess(newIndex);
                        }

                    } else {
                        if (newIndex % 2000 == 0) {
                            log.debug("Mapped " + newIndex + " records from " + tableName);
                        }
                    }

                } while (rs.next());
                log.info("Mapped " + newIndex + " records from " + tableName);

            } 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(IdTableMapper.class, ex);
            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:at.stefanproell.ResultSetVerification.ResultSetVerificationAPI.java

public int getResultSetRowCount(ResultSet rs) {
    int rows = 0;
    try {//w w w. j  a  va 2s . c o m
        if (rs.last()) {
            rows = rs.getRow();
            // Move to beginning
            rs.beforeFirst();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    this.logger.info("Returned rows: " + rows);
    return rows;

}