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:edu.ku.brc.specify.conversion.IdTableMapper.java

/**
 * Map all the old IDs to new IDs//from www .j  a  va 2s. co 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:edu.ku.brc.specify.conversion.IdTableMapper.java

/**
 * Map all the old IDs to new IDs/*from  ww  w.ja  va2s . c  om*/
 * @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:org.owasp.webgoat.plugin.introduction.SqlInjectionLesson6a.java

protected AttackResult injectableQuery(String accountName) {
    try {//from   w w w  .  j  av  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:Connexion.ChartDocteur.java

public ChartDocteur() {

    try {//  w  w  w.  ja va  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.owasp.webgoat.plugin.introduction.SqlInjectionLesson5a.java

protected AttackResult injectableQuery(String accountName) {
    try {//from w w w .j  ava 2s  .co  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())) {
                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: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  .java2  s. c  om
    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.introduction.SqlInjectionLesson5b.java

protected AttackResult injectableQuery(String accountName) {
    try {//from w  w  w  . ja  v a  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:SyncMusicServlet.java

private void processAlbumData(String name, String artist, String composer, String year) {
    Connection conn = null;/*from w w  w .  j  a  v a 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);

        String sql = "select * from album where album_title='" + name + "'";
        rs = stmt.executeQuery(sql);
        rs.next();
        if (rs.getRow() == 0) {
            pstmt = conn.prepareStatement(
                    "insert into album (album_title, album_artist, album_composer, release_year) values (?, ?, ?, ?)");
            pstmt.setString(1, name);
            pstmt.setString(2, artist);
            pstmt.setString(3, composer);
            pstmt.setString(4, year);
            pstmt.executeUpdate();
        }

        //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) {

        }
    }
}

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();//from   www  . j  ava  2s  .  c  o m
        int rowCount = rs.getRow();
        rs.beforeFirst();
        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:org.owasp.webgoat.plugin.CrossSiteScriptingLesson5b.java

protected AttackResult injectableQuery(String accountName) {
    try {//from  w  w  w .  java  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()));
    }
}