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:TestAccessExcel.java

public static void main(String args[]) {
    Connection conn = null;//from w w  w  .j  av  a 2s.  c  o m
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        stmt = conn.createStatement();
        String excelQuery = "select * from [Sheet1$]";
        rs = stmt.executeQuery(excelQuery);

        while (rs.next()) {
            System.out.println(rs.getString("BadgeNumber") + " " + rs.getString("FirstName") + " "
                    + rs.getString("LastName"));
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();

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

From source file:TypeMapDemo.java

public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {

    Properties p = new Properties();
    p.load(new FileInputStream("db.properties"));
    Class c = Class.forName(p.getProperty("db.driver"));
    System.out.println("Loaded driverClass " + c.getName());

    Connection con = DriverManager.getConnection(p.getProperty("db.url"), "student", "student");
    System.out.println("Got Connection " + con);

    Statement s = con.createStatement();
    int ret;/*w ww  .j  a va  2s  . com*/
    try {
        s.executeUpdate("drop table MR");
        s.executeUpdate("drop type MUSICRECORDING");
    } catch (SQLException andDoNothingWithIt) {
        // Should use "if defined" but not sure it works for UDTs...
    }
    ret = s.executeUpdate("create type MUSICRECORDING as object (" + "   id integer," + "   title varchar(20), "
            + "   artist varchar(20) " + ")");
    System.out.println("Created TYPE! Ret=" + ret);

    ret = s.executeUpdate("create table MR of MUSICRECORDING");
    System.out.println("Created TABLE! Ret=" + ret);

    int nRows = s.executeUpdate("insert into MR values(123, 'Greatest Hits', 'Ian')");
    System.out.println("inserted " + nRows + " rows");

    // Put the data class into the connection's Type Map
    // If the data class were not an inner class,
    // this would likely be done with Class.forName(...);
    Map map = con.getTypeMap();
    map.put("MUSICRECORDING", MusicRecording.class);
    con.setTypeMap(map);

    ResultSet rs = s.executeQuery("select * from MR where id = 123");
    //"select musicrecording(id,artist,title) from mr");
    rs.next();
    for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
        Object o = rs.getObject(i);
        System.out.print(o + "(Type " + o.getClass().getName() + ")\t");
    }
    System.out.println();
}

From source file:TableTypes.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//from  w w w.  j  av a2  s . com

    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        DatabaseMetaData dbmd = con.getMetaData();
        String dbmsName = dbmd.getDatabaseProductName();
        ResultSet rs = dbmd.getTableTypes();
        System.out.print("The following types of tables are ");
        System.out.println("available in " + dbmsName + ":  ");

        while (rs.next()) {
            String tableType = rs.getString("TABLE_TYPE");
            System.out.println("    " + tableType);
        }

        rs.close();
        con.close();

    } catch (SQLException ex) {
        System.err.print("SQLException: ");
        System.err.println(ex.getMessage());
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);// w w  w .j  av a 2 s .c o m

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Get cursor position
    int pos = resultSet.getRow();
    boolean b = resultSet.isBeforeFirst();

    // Move cursor to the first row
    resultSet.next();

    // Get cursor position
    pos = resultSet.getRow();
    b = resultSet.isFirst();

    // Move cursor to the last row
    resultSet.last();

    // Get cursor position
    pos = resultSet.getRow();
    b = resultSet.isLast();

    // Move cursor past last row
    resultSet.afterLast();

    // Get cursor position
    pos = resultSet.getRow();
    b = resultSet.isAfterLast();

}

From source file:JDBCQuery.java

public static void main(String[] av) {
    try {/*from www.j av  a2  s.c o m*/
        System.out.println("Loading Driver (with Class.forName)");
        // Load the jdbc-odbc bridge driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        // Enable logging
        // DriverManager.setLogStream(System.err);

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection("jdbc:odbc:Companies", "ian", ""); // user, passwd

        // Any warnings generated by the connect?
        checkForWarning(conn.getWarnings());

        System.out.println("Creating Statement");
        Statement stmt = conn.createStatement();

        System.out.println("Executing Query");
        ResultSet rs = stmt.executeQuery("SELECT * FROM Companies");

        System.out.println("Retrieving Results");
        int i = 0;
        while (rs.next()) {

            System.out.println("Retrieving Company ID");
            int x = rs.getInt("CustNO");
            System.out.println("Retrieving Name");
            String s = rs.getString("Company");

            System.out.println("ROW " + ++i + ": " + x + "; " + s + "; " + ".");

        }

        rs.close(); // All done with that resultset
        stmt.close(); // All done with that statement
        conn.close(); // All done with that DB connection

    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException e) {
        System.out.println("Database access failed " + e);
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    Connection conn = null;/*  w w w  .  j a v  a  2 s  . c  o  m*/
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        stmt = conn.createStatement();
        String query = "select EmployeeID, LastName, FirstName from Employees";
        rs = stmt.executeQuery(query);
        while (rs.next()) {
            System.out.println(rs.getString("EmployeeID") + " " + rs.getString("LastName") + " "
                    + rs.getString("FirstName"));
        }
    } catch (Exception e) {
        // handle the exception
        e.printStackTrace();
        System.err.println(e.getMessage());
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }
}

From source file:SetSavepoint.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";

    try {/* w w  w.ja  va  2 s  . c o  m*/

        Class.forName("myDriver.className");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {

        Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
        con.setAutoCommit(false);

        String query = "SELECT COF_NAME, PRICE FROM COFFEES " + "WHERE TOTAL > ?";
        String update = "UPDATE COFFEES SET PRICE = ? " + "WHERE COF_NAME = ?";

        PreparedStatement getPrice = con.prepareStatement(query);
        PreparedStatement updatePrice = con.prepareStatement(update);

        getPrice.setInt(1, 7000);
        ResultSet rs = getPrice.executeQuery();

        Savepoint save1 = con.setSavepoint();

        while (rs.next()) {
            String cof = rs.getString("COF_NAME");
            float oldPrice = rs.getFloat("PRICE");
            float newPrice = oldPrice + (oldPrice * .05f);
            updatePrice.setFloat(1, newPrice);
            updatePrice.setString(2, cof);
            updatePrice.executeUpdate();
            System.out.println("New price of " + cof + " is " + newPrice);
            if (newPrice > 11.99) {
                con.rollback(save1);
            }

        }

        getPrice = con.prepareStatement(query);
        updatePrice = con.prepareStatement(update);

        getPrice.setInt(1, 8000);

        rs = getPrice.executeQuery();
        System.out.println();

        Savepoint save2 = con.setSavepoint();

        while (rs.next()) {
            String cof = rs.getString("COF_NAME");
            float oldPrice = rs.getFloat("PRICE");
            float newPrice = oldPrice + (oldPrice * .05f);
            updatePrice.setFloat(1, newPrice);
            updatePrice.setString(2, cof);
            updatePrice.executeUpdate();
            System.out.println("New price of " + cof + " is " + newPrice);
            if (newPrice > 11.99) {
                con.rollback(save2);
            }
        }

        con.commit();

        Statement stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT COF_NAME, " + "PRICE FROM COFFEES");

        System.out.println();
        while (rs.next()) {
            String name = rs.getString("COF_NAME");
            float price = rs.getFloat("PRICE");
            System.out.println("Current price of " + name + " is " + price);
        }

        con.close();

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

}

From source file:BatchUpdate.java

public static void main(String args[]) throws SQLException {

    ResultSet rs = null;/*from   w  ww . j a  v a  2  s. c  o m*/
    PreparedStatement ps = null;

    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;
    Statement stmt;
    try {

        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {

        con = DriverManager.getConnection(url, "myLogin", "myPassword");
        con.setAutoCommit(false);

        stmt = con.createStatement();

        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)");

        int[] updateCounts = stmt.executeBatch();
        con.commit();
        con.setAutoCommit(true);

        ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");

        System.out.println("Table COFFEES after insertion:");
        while (uprs.next()) {
            String name = uprs.getString("COF_NAME");
            int id = uprs.getInt("SUP_ID");
            float price = uprs.getFloat("PRICE");
            int sales = uprs.getInt("SALES");
            int total = uprs.getInt("TOTAL");
            System.out.print(name + "   " + id + "   " + price);
            System.out.println("   " + sales + "   " + total);
        }

        uprs.close();
        stmt.close();
        con.close();

    } catch (BatchUpdateException b) {
        System.err.println("-----BatchUpdateException-----");
        System.err.println("SQLState:  " + b.getSQLState());
        System.err.println("Message:  " + b.getMessage());
        System.err.println("Vendor:  " + b.getErrorCode());
        System.err.print("Update counts:  ");
        int[] updateCounts = b.getUpdateCounts();
        for (int i = 0; i < updateCounts.length; i++) {
            System.err.print(updateCounts[i] + "   ");
        }
        System.err.println("");

    } catch (SQLException ex) {
        System.err.println("-----SQLException-----");
        System.err.println("SQLState:  " + ex.getSQLState());
        System.err.println("Message:  " + ex.getMessage());
        System.err.println("Vendor:  " + ex.getErrorCode());
    }
}

From source file:SQLStatement.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*from www  .j  ava  2 s. c om*/
    String query = "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from COFFEES, SUPPLIERS "
            + "where SUPPLIERS.SUP_NAME like 'Acme, Inc.' and " + "SUPPLIERS.SUP_ID = COFFEES.SUP_ID";
    Statement stmt;

    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery(query);
        ResultSetMetaData rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        int rowCount = 1;
        while (rs.next()) {
            System.out.println("Row " + rowCount + ":  ");
            for (int i = 1; i <= numberOfColumns; i++) {
                System.out.print("   Column " + i + ":  ");
                System.out.println(rs.getString(i));
            }
            System.out.println("");
            rowCount++;
        }
        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.print("SQLException: ");
        System.err.println(ex.getMessage());
    }
}

From source file:DemoGetGeneratedKeysMySQL.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement stmt = null;//from  w ww  . jav a 2 s . c  o  m
    ResultSet rs = null;
    try {
        conn = getConnection();
        stmt = conn.createStatement();
        stmt.executeUpdate("insert into animals_table (name) values('newName')");
        rs = stmt.getGeneratedKeys();
        while (rs.next()) {
            ResultSetMetaData rsMetaData = rs.getMetaData();
            int columnCount = rsMetaData.getColumnCount();

            for (int i = 1; i <= columnCount; i++) {
                String key = rs.getString(i);
                System.out.println("key " + i + " is " + key);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}