Example usage for java.sql ResultSet next

List of usage examples for java.sql ResultSet next

Introduction

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

Prototype

boolean next() throws SQLException;

Source Link

Document

Moves the cursor forward one row from its current position.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ResultSet rs = null;
    Connection conn = null;/*from w  w w.  j  a  va2  s . c o m*/
    PreparedStatement pstmt = null;
    PreparedStatement pstmt2 = null;
    conn = getOracleConnection();
    String[] columnNames = { "id", "name", "content", "date_created" };
    Object[] inputValues = new Object[columnNames.length];
    inputValues[0] = new java.math.BigDecimal(100);
    inputValues[1] = new String("String Value");
    inputValues[2] = new String("This is my resume.");
    inputValues[3] = new Timestamp((new java.util.Date()).getTime());

    // prepare blob object from an existing binary column
    String insert = "insert into resume (id, name, content, date_created ) values(?, ?, ?, ?)";
    pstmt = conn.prepareStatement(insert);

    pstmt.setObject(1, inputValues[0]);
    pstmt.setObject(2, inputValues[1]);
    pstmt.setObject(3, inputValues[2]);
    pstmt.setObject(4, inputValues[3]);

    pstmt.executeUpdate();
    String query = "select id, name, content, date_created from resume where id=?";

    pstmt2 = conn.prepareStatement(query);
    pstmt2.setObject(1, inputValues[0]);
    rs = pstmt2.executeQuery();
    Object[] outputValues = new Object[columnNames.length];
    if (rs.next()) {
        for (int i = 0; i < columnNames.length; i++) {
            outputValues[i] = rs.getObject(i + 1);
        }
    }
    System.out.println("id=" + ((java.math.BigDecimal) outputValues[0]).toString());
    System.out.println("name=" + ((String) outputValues[1]));
    System.out.println("content=" + ((Clob) outputValues[2]));
    System.out.println("date_created=" + ((java.sql.Date) outputValues[3]).toString());

    rs.close();
    pstmt.close();
    pstmt2.close();
    conn.close();

}

From source file:de.tudarmstadt.ukp.csniper.resbuild.EvaluationItemFixer2.java

public static void main(String[] args) {
    connect(HOST, DATABASE, USER, PASSWORD);

    Map<Integer, String> items = new HashMap<Integer, String>();
    Map<Integer, String> failed = new HashMap<Integer, String>();

    // fetch coveredTexts of dubious items and clean it
    PreparedStatement select = null;
    PreparedStatement update = null;
    try {/*from ww w  .  ja  va  2  s  .com*/
        StringBuilder selectQuery = new StringBuilder();
        selectQuery.append("SELECT * FROM cachedparse WHERE pennTree = 'ERROR' OR pennTree = ''");

        select = connection.prepareStatement(selectQuery.toString());
        log.info("Running query [" + selectQuery.toString() + "].");
        ResultSet rs = select.executeQuery();

        //         CSVWriter writer;
        String text;
        JCas jcas = JCasFactory.createJCas();
        String updateQuery = "UPDATE CachedParse SET pennTree = ? WHERE collectionId = ? AND documentId = ? AND beginOffset = ? AND endOffset = ?";
        update = connection.prepareStatement(updateQuery);
        //         File base = new File("");

        AnalysisEngine sentences = createEngine(DummySentenceSplitter.class);
        AnalysisEngine tokenizer = createEngine(StanfordSegmenter.class,
                StanfordSegmenter.PARAM_CREATE_SENTENCES, false, StanfordSegmenter.PARAM_CREATE_TOKENS, true);
        AnalysisEngine parser = createEngine(StanfordParser.class, StanfordParser.PARAM_WRITE_CONSTITUENT, true,
                //               StanfordParser.PARAM_CREATE_DEPENDENCY_TAGS, true,
                StanfordParser.PARAM_WRITE_PENN_TREE, true, StanfordParser.PARAM_LANGUAGE, "en",
                StanfordParser.PARAM_VARIANT, "factored");

        while (rs.next()) {
            String collectionId = rs.getString("collectionId");
            String documentId = rs.getString("documentId");
            int beginOffset = rs.getInt("beginOffset");
            int endOffset = rs.getInt("endOffset");
            text = retrieveCoveredText(collectionId, documentId, beginOffset, endOffset);

            jcas.setDocumentText(text);
            jcas.setDocumentLanguage("en");
            sentences.process(jcas);
            tokenizer.process(jcas);
            parser.process(jcas);

            //            writer = new CSVWriter(new FileWriter(new File(base, documentId + ".csv"));

            System.out.println("Updating " + text);
            for (PennTree p : JCasUtil.select(jcas, PennTree.class)) {
                String tree = StringUtils.normalizeSpace(p.getPennTree());
                update.setString(1, tree);
                update.setString(2, collectionId);
                update.setString(3, documentId);
                update.setInt(4, beginOffset);
                update.setInt(5, endOffset);
                update.executeUpdate();
                System.out.println("with tree " + tree);
                break;
            }
            jcas.reset();
        }
    } catch (SQLException e) {
        log.error("Exception while selecting: " + e.getMessage());
    } catch (UIMAException e) {
        e.printStackTrace();
    } finally {
        closeQuietly(select);
        closeQuietly(update);
    }

    // write logs
    //      BufferedWriter bwf = null;
    //      BufferedWriter bws = null;
    //      try {
    //         bwf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(
    //               LOG_FAILED)), "UTF-8"));
    //         for (Entry<Integer, String> e : failed.entrySet()) {
    //            bwf.write(e.getKey() + " - " + e.getValue() + "\n");
    //         }
    //
    //         bws = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(
    //               LOG_SUCCESSFUL)), "UTF-8"));
    //         for (Entry<Integer, String> e : items.entrySet()) {
    //            bws.write(e.getKey() + " - " + e.getValue() + "\n");
    //         }
    //      }
    //      catch (IOException e) {
    //         log.error("Got an IOException while writing the log files.");
    //      }
    //      finally {
    //         IOUtils.closeQuietly(bwf);
    //         IOUtils.closeQuietly(bws);
    //      }

    log.info("Texts for [" + items.size() + "] items need to be cleaned up.");

    // update the dubious items with the cleaned coveredText
    //      PreparedStatement update = null;
    //      try {
    //         String updateQuery = "UPDATE EvaluationItem SET coveredText = ? WHERE id = ?";
    //
    //         update = connection.prepareStatement(updateQuery);
    //         int i = 0;
    //         for (Entry<Integer, String> e : items.entrySet()) {
    //            int id = e.getKey();
    //            String coveredText = e.getValue();
    //
    //            // update item in database
    //            update.setString(1, coveredText);
    //            update.setInt(2, id);
    //            update.executeUpdate();
    //            log.debug("Updating " + id + " with [" + coveredText + "]");
    //
    //            // show percentage of updated items
    //            i++;
    //            int part = (int) Math.ceil((double) items.size() / 100);
    //            if (i % part == 0) {
    //               log.info(i / part + "% finished (" + i + "/" + items.size() + ").");
    //            }
    //         }
    //      }
    //      catch (SQLException e) {
    //         log.error("Exception while updating: " + e.getMessage());
    //      }
    //      finally {
    //         closeQuietly(update);
    //      }

    closeQuietly(connection);
}

From source file:com.intelius.iap4.TigerLineHit.java

public static void main(String[] args) {

    String _tigerDs = "jdbc:h2:/home/sxu/playground/tiger";
    ResultSet rs = null;
    PreparedStatement ps = null;/*  ww  w . j  a v  a2 s  . c o m*/
    List<TigerLineHit> ret = new ArrayList<TigerLineHit>();
    try {
        //      if (_tigerDs instanceof JdbcDataSource) {
        //        JdbcDataSource ds = (JdbcDataSource) _tigerDs;
        //        conn = ds.getPooledConnection().getConnection();
        //      }else{
        //        conn = _tigerDs.getConnection();
        //      }

        //try address "540 westerly parkway, state college, pa 16801"

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection(_tigerDs, "sa", "");
        ps = conn.prepareStatement(generateSelectQuery("PA"));
        int i = 1;
        String streetNum = "540";
        String zip = "16801";
        ps.setString(i++, "Westerly");
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, zip);
        ps.setString(i++, zip);
        rs = ps.executeQuery();
        while (rs.next()) {
            TigerLineHit hit = new TigerLineHit();
            hit.streetNum = streetNum;
            hit.tlid = rs.getLong("tlid");
            hit.frAddL = rs.getString("fraddl");
            hit.frAddR = rs.getString("fraddr");
            hit.toAddL = rs.getString("toaddl");
            hit.toAddR = rs.getString("toaddr");
            hit.zipL = rs.getString("zipL");
            hit.zipR = rs.getString("zipR");
            hit.toLat = rs.getFloat("tolat");
            hit.toLon = rs.getFloat("tolong");
            hit.frLat = rs.getFloat("frlat");
            hit.frLon = rs.getFloat("tolong");
            hit.lat1 = rs.getFloat("lat1");
            hit.lat2 = rs.getFloat("lat2");
            hit.lat3 = rs.getFloat("lat3");
            hit.lat4 = rs.getFloat("lat4");
            hit.lat5 = rs.getFloat("lat5");
            hit.lat6 = rs.getFloat("lat6");
            hit.lat7 = rs.getFloat("lat7");
            hit.lat8 = rs.getFloat("lat8");
            hit.lat9 = rs.getFloat("lat9");
            hit.lat10 = rs.getFloat("lat10");
            hit.lon1 = rs.getFloat("long1");
            hit.lon2 = rs.getFloat("long2");
            hit.lon3 = rs.getFloat("long3");
            hit.lon4 = rs.getFloat("long4");
            hit.lon5 = rs.getFloat("long5");
            hit.lon6 = rs.getFloat("long6");
            hit.lon7 = rs.getFloat("long7");
            hit.lon8 = rs.getFloat("long8");
            hit.lon9 = rs.getFloat("long9");
            hit.lon10 = rs.getFloat("long10");
            hit.fedirp = rs.getString("fedirp");
            hit.fetype = rs.getString("fetype");
            hit.fedirs = rs.getString("fedirs");
            ret.add(hit);

            //            
            System.out.println(ret.toString());
            //
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(ps);
    }
    //return ret;
}

From source file:com.sapienter.jbilling.tools.ConvertToBinHexa.java

/**
 * @param args//  w w w . j ava 2s.c  o m
 */
public static void main(String[] args) {
    String driver = null;

    if (args.length < 3) {
        System.err.println("Usage: url username password [driver]");
        System.exit(1);
        return;
    }
    if (args.length < 4) {
        driver = "org.postgresql.Driver";
    } else {
        driver = args[3];
    }

    System.out.println("Converting credit cards ... ");
    int count = 0;
    try {
        connection = getConnection(args[0], args[1], args[2], driver);
        ResultSet rows = getCCRowsToUpdate();
        while (rows == null) { //rows.next() - skip CC
            int rowId = rows.getInt(1);
            String cryptedNumber = rows.getString(2);
            String cryptedName = rows.getString(3);
            int userId = rows.getInt(4);

            JBCrypto oldCrypt = JBCrypto.getCreditCardCrypto();
            oldCrypt.setUseHexForBinary(false);
            String plainNumber;
            try {
                plainNumber = oldCrypt.decrypt(cryptedNumber);
            } catch (Exception e) {
                plainNumber = "Not available";
                System.out.println("User id " + userId + " cc id " + rowId + " with bad cc number");
            }
            String plainName;
            try {
                plainName = oldCrypt.decrypt(cryptedName);
            } catch (RuntimeException e) {
                plainName = "Not available";
                System.out.println("User id " + userId + " cc id " + rowId + " with bad cc name");
            }
            // now recrypt using the new way
            JBCrypto newCrypt = JBCrypto.getCreditCardCrypto();
            newCrypt.setUseHexForBinary(true);
            cryptedName = newCrypt.encrypt(plainName);
            cryptedNumber = newCrypt.encrypt(plainNumber);
            //System.out.println("new " + cryptedName + " and " + cryptedNumber);
            updateCCRow(rowId, cryptedName, cryptedNumber);
            count++;
        }
        rows.close();

        System.out.println("Converting user passwords ... ");
        count = 0;
        rows = getUserRowsToUpdate();
        while (rows.next()) {
            int rowId = rows.getInt(1);
            String oldPassword = rows.getString(2);

            try {
                String newPassword = Util.binaryToString(Base64.decodeBase64(oldPassword.getBytes()));
                System.out.println("new " + newPassword + " old " + oldPassword);
                updateUserRow(rowId, newPassword);
                count++;
            } catch (Exception e) {
                System.out.println("Error with password " + oldPassword + " :" + e.getMessage());
            }
        }
        rows.close();

        connection.close();
    } catch (Exception e) {
        System.err.println("Error! " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
    System.out.println("Finished! " + count + " rows populated");

}

From source file:Main.java

public static void main(String[] argv) {
    Connection connection = null;
    Statement statement;//w  w  w . j  a  va2s. c  o m
    ResultSet rs;
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB");
        connection = ds.getConnection();

        DatabaseMetaData md = connection.getMetaData();
        statement = connection.createStatement();

        System.out.println("getURL() - " + md.getURL());
        System.out.println("getUserName() - " + md.getUserName());
        System.out.println("getDatabaseProductVersion - " + md.getDatabaseProductVersion());
        System.out.println("getDriverMajorVersion - " + md.getDriverMajorVersion());
        System.out.println("getDriverMinorVersion - " + md.getDriverMinorVersion());
        System.out.println("nullAreSortedHigh - " + md.nullsAreSortedHigh());

        System.out.println("<H1>Feature Support</H1>");
        System.out.println(
                "supportsAlterTableWithDropColumn - " + md.supportsAlterTableWithDropColumn() + "<BR>");
        System.out.println("supportsBatchUpdates - " + md.supportsBatchUpdates());
        System.out.println("supportsTableCorrelationNames - " + md.supportsTableCorrelationNames());
        System.out.println("supportsPositionedDelete - " + md.supportsPositionedDelete());
        System.out.println("supportsFullOuterJoins - " + md.supportsFullOuterJoins());
        System.out.println("supportsStoredProcedures - " + md.supportsStoredProcedures());
        System.out.println("supportsMixedCaseQuotedIdentifiers - " + md.supportsMixedCaseQuotedIdentifiers());
        System.out.println("supportsANSI92EntryLevelSQL - " + md.supportsANSI92EntryLevelSQL());
        System.out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar());
        System.out.println("getMaxRowSize - " + md.getMaxRowSize());
        System.out.println("getMaxStatementLength - " + md.getMaxStatementLength());
        System.out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect());
        System.out.println("getMaxConnections - " + md.getMaxConnections());
        System.out.println("getMaxCharLiteralLength - " + md.getMaxCharLiteralLength());

        System.out.println("getTableTypes()");
        rs = md.getTableTypes();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
        System.out.println("getTables()");
        rs = md.getTables("accounts", "", "%", new String[0]);
        while (rs.next()) {
            System.out.println(rs.getString("TABLE_NAME"));
        }
        System.out.println("Transaction Support");
        System.out.println("getDefaultTransactionIsolation() - " + md.getDefaultTransactionIsolation());
        System.out
                .println("dataDefinitionIgnoredInTransactions() - " + md.dataDefinitionIgnoredInTransactions());

        System.out.println("General Source Information");
        System.out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect());
        System.out.println("getMaxColumnsInTable - " + md.getMaxColumnsInTable());
        System.out.println("getTimeDateFunctions - " + md.getTimeDateFunctions());
        System.out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar());

        System.out.println("getTypeInfo()");
        rs = md.getTypeInfo();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ExecuteMethod.java

public static void processExecute(Statement stmt, boolean executeResult) throws SQLException {
    if (!executeResult) {
        int updateCount = stmt.getUpdateCount();
        System.out.println(updateCount + " row was " + "inserted into Employee table.");

    } else {// w w  w.  j av  a2  s. co m
        ResultSet rs = stmt.getResultSet();
        while (rs.next()) {
            System.out.println(rs.getInt("SSN") + rs.getString("Name") + rs.getDouble("Salary")
                    + rs.getDate("Hiredate") + rs.getInt("Loc_id"));

        }
    }
}

From source file:Main.java

public static void getTables(Connection conn) throws Exception {
    String TABLE_NAME = "TABLE_NAME";
    String TABLE_SCHEMA = "TABLE_SCHEM";
    String[] TABLE_TYPES = { "TABLE" };
    DatabaseMetaData dbmd = conn.getMetaData();

    ResultSet tables = dbmd.getTables(null, null, null, TABLE_TYPES);
    while (tables.next()) {
        System.out.println(tables.getString(TABLE_NAME));
        System.out.println(tables.getString(TABLE_SCHEMA));
    }/*ww  w . j  a v a  2  s  .c  o m*/
}

From source file:UpdateableRs.java

public static void printRs(ResultSet rs) throws SQLException {
    rs.beforeFirst();//from  w w  w . j av  a2s . c  om

    while (rs.next()) {
        int ssn = rs.getInt("ssn");
        String name = rs.getString("name");
        double salary = rs.getDouble("salary");

        System.out.print("Row Number=" + rs.getRow());
        System.out.print(", SSN: " + ssn);
        System.out.print(", Name: " + name);
        System.out.println(", Salary: $" + salary);
    }
    System.out.println();
}

From source file:Main.java

public static Object readJavaObject(Connection conn, long id) throws Exception {
    PreparedStatement pstmt = conn.prepareStatement(READ_OBJECT_SQL);
    pstmt.setLong(1, id);/*  w w w  .j a  va2s  .c om*/
    ResultSet rs = pstmt.executeQuery();
    rs.next();
    Object object = rs.getObject("object_value");
    String className = object.getClass().getName();
    rs.close();
    pstmt.close();
    return object;
}

From source file:Main.java

public static Object readJavaObject(Connection conn, long id) throws Exception {
    PreparedStatement pstmt = conn.prepareStatement(READ_OBJECT_SQL);
    pstmt.setLong(1, id);/*ww w .  j  av a2 s.  c  om*/
    ResultSet rs = pstmt.executeQuery();
    rs.next();
    Object object = rs.getObject(1);
    String className = object.getClass().getName();
    rs.close();
    pstmt.close();
    return object;
}