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:hotelregistration.HotelRegistration.java

/**
 * @param args the command line arguments
 *///from   w  w  w .  j  a v  a  2s. co m
public static void main(String[] args) {

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    DBConnection dbCon = new DBConnection();
    dbCon.getConnetion();

    try {

        Statement st = dbCon.getConnetion().createStatement();
        ResultSet rs = st.executeQuery("SELECT NAME, ADDRESS FROM HOTEL");
        Hotel hotel = (Hotel) context.getBean("hotel");
        while (rs.next()) {
            hotel.setName(rs.getString("name"));
            hotel.setAddress(rs.getString("address"));
            System.out.println("1. Nombre: " + hotel.getName() + ", Direccion: " + hotel.getAddress());
        }

        HotelDao hotelDao = (HotelDao) context.getBean("hotelDao");
        Hotel hotel1 = hotelDao.findHotel("Moon");

        Hotel hotel2 = new Hotel();
        hotel2.setName("Jupiter");
        hotel2.setAddress("Jupiter");
        hotelDao.insertHotel(hotel2);

        System.out.println("2. Nombre: " + hotel1.getName() + ", Direccion: " + hotel1.getAddress());

    } catch (SQLException ex) {
        Logger.getLogger(HotelRegistration.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar);");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;
    DatabaseMetaData meta = conn.getMetaData();
    rs = meta.getTables(null, null, null, new String[] { "TABLE" });

    while (rs.next()) {
        String tableName = rs.getString("TABLE_NAME");
        System.out.println("tableName=" + tableName);
    }/*from w  w w .  j  a va  2 s.  c  o m*/

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
    st = conn.createStatement();//from ww  w  .j  av  a 2 s  .  co m
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    rs = st.executeQuery("SELECT COUNT(*) FROM survey");
    // get the number of rows from the result set
    rs.next();
    int rowCount = rs.getInt(1);
    System.out.println(rowCount);

    rs.close();
    st.close();
    conn.close();

}

From source file:ResultSetExample.java

public static void main(String args[]) {
    try {//from  w w  w .  j  a va 2  s  .c o  m
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        Connection con = DriverManager.getConnection("jdbc:odbc:Inventory", "", "");

        Statement stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery("SELECT SupplierName,ProductName, Price "
                + "FROM ProductSuppliersView WHERE CategoryName LIKE '%BEVERAGES%' ");
        while (rs.next()) {
            String supplier = rs.getString("SupplierName");
            String product = rs.getString("ProductName");
            int price = rs.getInt("Price");

            System.out.println(supplier + " sells " + product + " for $" + price);
        }

        stmt.close();
        con.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar);");
    st.executeUpdate("create view surveyView as (select * from survey);");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;
    DatabaseMetaData meta = conn.getMetaData();
    rs = meta.getTables(null, null, null, new String[] { "VIEW" });

    while (rs.next()) {
        String tableName = rs.getString("TABLE_NAME");
        System.out.println("tableName=" + tableName);
    }/*from  w w  w .  j  a v a 2  s.c  om*/

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    // Move cursor to the beginning, before the first row.
    // cursor position is 0.
    rs.beforeFirst();/*from w  w w. ja v  a2 s .  c  o m*/
    rs.next();
    // Get data at cursor
    String id = rs.getString("id");
    System.out.println(id);

    rs.close();
    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) {
    Connection conn = null;//from w  w  w.j a  va2  s . c  o  m
    Statement stmt = null;
    try {
        // STEP 2: Register JDBC driver
        Class.forName(JDBC_DRIVER);

        // STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        // STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT id, first, last, age FROM Employees";
        stmt.executeUpdate(
                "CREATE TABLE Employees ( id INTEGER IDENTITY, first VARCHAR(256),  last VARCHAR(256),age INTEGER)");
        stmt.executeUpdate("INSERT INTO Employees VALUES(1,'Jack','Smith', 100)");

        ResultSet rs = stmt.executeQuery(sql);

        // STEP 5: Extract data from result set
        while (rs.next()) {
            // Retrieve by column name
            int id = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            System.out.print("ID: " + id);
            System.out.print(", Age: " + age);
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
        }
        // STEP 6: Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
    System.out.println("Goodbye!");
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;
    DatabaseMetaData meta = conn.getMetaData();
    rs = meta.getTables(null, null, null, new String[] { "TABLE", "VIEW" });
    while (rs.next()) {
        String tableOrViewName = rs.getString("TABLE_NAME");
        System.out.println("getTableNames(): tableOrViewName=" + tableOrViewName);
    }/*from   www .  ja  v  a 2s . c o m*/

    st.close();
    conn.close();
}

From source file:TransactionPairs.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con = null;//from   ww  w.  ja v a 2s. com
    Statement stmt;
    PreparedStatement updateSales;
    PreparedStatement updateTotal;
    String updateString = "update COFFEES " + "set SALES = ? where COF_NAME like ?";

    String updateStatement = "update COFFEES " + "set TOTAL = TOTAL + ? where COF_NAME like ?";
    String query = "select COF_NAME, SALES, TOTAL from COFFEES";

    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");

        updateSales = con.prepareStatement(updateString);
        updateTotal = con.prepareStatement(updateStatement);
        int[] salesForWeek = { 175, 150, 60, 155, 90 };
        String[] coffees = { "Colombian", "French_Roast", "Espresso", "Colombian_Decaf", "French_Roast_Decaf" };
        int len = coffees.length;
        con.setAutoCommit(false);
        for (int i = 0; i < len; i++) {
            updateSales.setInt(1, salesForWeek[i]);
            updateSales.setString(2, coffees[i]);
            updateSales.executeUpdate();

            updateTotal.setInt(1, salesForWeek[i]);
            updateTotal.setString(2, coffees[i]);
            updateTotal.executeUpdate();
            con.commit();
        }

        con.setAutoCommit(true);

        updateSales.close();
        updateTotal.close();

        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            String c = rs.getString("COF_NAME");
            int s = rs.getInt("SALES");
            int t = rs.getInt("TOTAL");
            System.out.println(c + "     " + s + "    " + t);
        }

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

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
        if (con != null) {
            try {
                System.err.print("Transaction is being ");
                System.err.println("rolled back");
                con.rollback();
            } catch (SQLException excep) {
                System.err.print("SQLException: ");
                System.err.println(excep.getMessage());
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");

    ResultSet rsColumns = null;
    DatabaseMetaData meta = conn.getMetaData();
    rsColumns = meta.getColumns(null, "%", "code", "%");

    while (rsColumns.next()) {
        String columnType = rsColumns.getString("TYPE_NAME");
        String columnName = rsColumns.getString("COLUMN_NAME");
        int size = rsColumns.getInt("COLUMN_SIZE");
        int nullable = rsColumns.getInt("NULLABLE");
        int position = rsColumns.getInt("ORDINAL_POSITION");

        System.out.println("column name=" + columnName);
        System.out.println("type=" + columnType);
        System.out.println("size=" + size);
        if (nullable == DatabaseMetaData.columnNullable) {
            System.out.println("nullable is true");
        } else {/* www.j a  v  a2 s.c  om*/
            System.out.println("nullable is false");
        }
        System.out.println("position" + position);
    }

    conn.close();
}