Example usage for java.sql PreparedStatement executeQuery

List of usage examples for java.sql PreparedStatement executeQuery

Introduction

In this page you can find the example usage for java.sql PreparedStatement executeQuery.

Prototype

ResultSet executeQuery() throws SQLException;

Source Link

Document

Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    Connection con = null;//from   ww w . j a  v  a2  s  . c  om
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection("jdbc:oracle:thin:@192.201.32.92:1521:psprd1", "username", "password");
    String query = null;
    ResultSet rset = null;
    query = "UPDATE t1 " + " SET id = ?";
    PreparedStatement stmt = con.prepareStatement(query);
    // stmt.setInt(paramIndex++, null);
    stmt.setNull(1, java.sql.Types.INTEGER);
    stmt.executeUpdate();
    stmt.close();
    query = "select id from t1 ";
    stmt = con.prepareStatement(query);
    rset = stmt.executeQuery();
    rset.next();
    System.out.println(rset.getString("id"));
    rset.close();
    stmt.close();
    con.close();
}

From source file:DemoDisplayBinaryDataFromDatabase.java

public static void main(String args[]) throws Exception {
    Connection conn = null;/*from  w w  w .j  a va  2s .  co  m*/
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    String query = "SELECT raw_column, long_raw_column FROM binary_table WHERE id = ?";
    try {
        conn = getConnection();
        Object[] results = new Object[2];
        pstmt = conn.prepareStatement(query);
        pstmt.setString(1, "0001");
        rs = pstmt.executeQuery();
        rs.next();
        // materialize binary data onto client
        results[0] = rs.getBytes("RAW_COLUMN");
        results[1] = rs.getBytes("LONG_RAW_COLUMN");
    } finally {
        rs.close();
        pstmt.close();
        conn.close();
    }
}

From source file:SelectRecordsUsingPreparedStatement.java

public static void main(String[] args) {
    ResultSet rs = null;//from www.  j  a va 2s. c o  m
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
        conn = getConnection();
        String query = "select deptno, deptname, deptloc from dept where deptno > ?";

        pstmt = conn.prepareStatement(query); // create a statement
        pstmt.setInt(1, 1001); // set input parameter
        rs = pstmt.executeQuery();
        // extract data from the ResultSet
        while (rs.next()) {
            int dbDeptNumber = rs.getInt(1);
            String dbDeptName = rs.getString(2);
            String dbDeptLocation = rs.getString(3);
            System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:DemoPreparedStatementSetClob.java

public static void main(String[] args) throws Exception {
    String id = "0001";
    String newID = "0002";

    ResultSet rs = null;//from  w w  w. java 2 s.  com
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
        conn = getConnection();
        // begin transaction
        conn.setAutoCommit(false);
        String query1 = "select clob_column from clob_table where id = ?";
        pstmt = conn.prepareStatement(query1);
        pstmt.setString(1, id);
        rs = pstmt.executeQuery();
        rs.next();
        java.sql.Clob clob = (java.sql.Clob) rs.getObject(1);
        String query = "insert into clob_table(id, clob_column) values(?, ?)";
        pstmt = conn.prepareStatement(query);
        pstmt.setString(1, newID);
        pstmt.setClob(2, clob);

        int rowCount = pstmt.executeUpdate();
        System.out.println("rowCount=" + rowCount);
        conn.commit();
    } finally {
        rs.close();
        pstmt.close();
        conn.close();
    }
}

From source file:SetSavepoint.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";

    try {//from  www . jav  a2s .  com

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

public static void main(String[] args) throws Exception {
    String id = "0001";
    String newID = "0002";

    ResultSet rs = null;// www.  ja v  a2  s  .c  o  m
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
        conn = getConnection();
        // begin transaction
        conn.setAutoCommit(false);
        String query1 = "select clob_column from clob_table where id = ?";
        pstmt = conn.prepareStatement(query1);
        pstmt.setString(1, id);
        rs = pstmt.executeQuery();
        rs.next();
        java.sql.Clob clob = (java.sql.Clob) rs.getObject(1);
        String query = "insert into clob_table(id, clob_column) values(?, ?)";
        pstmt = conn.prepareStatement(query);
        pstmt.setString(1, newID);
        pstmt.setClob(2, clob);

        // execute query, and return number of rows created
        int rowCount = pstmt.executeUpdate();
        System.out.println("rowCount=" + rowCount);
        // end transaction
        conn.commit();
    } finally {
        rs.close();
        pstmt.close();
        conn.close();
    }
}

From source file:Batch.java

static public void main(String[] args) {
    Connection conn = null;//from   w  ww  . ja v a2s . co m

    try {
        ArrayList breakable = new ArrayList();
        PreparedStatement stmt;
        Iterator users;
        ResultSet rs;

        Class.forName(args[0]).newInstance();
        conn = DriverManager.getConnection(args[1], args[2], args[3]);
        stmt = conn.prepareStatement("SELECT user_id, password " + "FROM user");
        rs = stmt.executeQuery();
        while (rs.next()) {
            String uid = rs.getString(1);
            String pw = rs.getString(2);

            // Assume PasswordCracker is some class that provides
            // a single static method called crack() that attempts
            // to run password cracking routines on the password
            //                if( PasswordCracker.crack(uid, pw) ) {
            //                  breakable.add(uid);
            //            }
        }
        stmt.close();
        if (breakable.size() < 1) {
            return;
        }
        stmt = conn.prepareStatement("UPDATE user " + "SET bad_password = 'Y' " + "WHERE uid = ?");
        users = breakable.iterator();
        while (users.hasNext()) {
            String uid = (String) users.next();

            stmt.setString(1, uid);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:DemoUpdatableResultSet.java

public static void main(String[] args) {
    ResultSet rs = null;//from  ww w  .  ja v a 2s  .  c o  m
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
        conn = getConnection();
        String query = "select id, name, age from employees where age > ?";
        pstmt = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        pstmt.setInt(1, 20); // set input values
        rs = pstmt.executeQuery(); // create an updatable ResultSet
                                   // update a column value in the current row.
        rs.absolute(2); // moves the cursor to the 2nd row of rs
        rs.updateString("name", "newName"); // updates the 'name' column of row 2 to newName
        rs.updateRow(); // updates the row in the data source
                        // insert column values into the insert row.
        rs.moveToInsertRow(); // moves cursor to the insert row
        rs.updateInt(1, 1234); // 1st column id=1234
        rs.updateString(2, "newName"); // updates the 2nd column
        rs.updateInt(3, 99); // updates the 3rd column to 99
        rs.insertRow();
        rs.moveToCurrentRow();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:InsertStores.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//ww  w .j  a  v a 2s .  c  o  m
    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();
        con.setAutoCommit(false);

        String insertStore1 = "INSERT INTO STORES VALUES (" + "100001, "
                + "ADDRESS(888, 'Main_Street', 'Rancho_Alegre', " + "'CA', '94049'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))";

        stmt.addBatch(insertStore1);

        String insertStore2 = "INSERT INTO STORES VALUES (" + "100002, "
                + "ADDRESS(1560, 'Alder', 'Ochos_Pinos', " + "'CA', '94049'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))";

        stmt.addBatch(insertStore2);

        String insertStore3 = "INSERT INTO STORES VALUES (" + "100003, "
                + "ADDRESS(4344, 'First_Street', 'Verona', " + "'CA', '94545'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))";

        stmt.addBatch(insertStore3);

        String insertStore4 = "INSERT INTO STORES VALUES (" + "100004, "
                + "ADDRESS(321, 'Sandy_Way', 'La_Playa', " + "'CA', '94544'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))";

        stmt.addBatch(insertStore4);

        String insertStore5 = "INSERT INTO STORES VALUES (" + "100005, "
                + "ADDRESS(1000, 'Clover_Road', 'Happyville', " + "'CA', '90566'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000003))";

        stmt.addBatch(insertStore5);

        int[] updateCounts = stmt.executeBatch();

        ResultSet rs = stmt.executeQuery("SELECT * FROM STORES");

        System.out.println("Table STORES after insertion:");
        System.out.println("STORE_NO  LOCATION          COF_TYPE     MGR");
        while (rs.next()) {
            int storeNo = rs.getInt("STORE_NO");
            Struct location = (Struct) rs.getObject("LOCATION");
            Object[] locAttrs = location.getAttributes();
            Array coffeeTypes = rs.getArray("COF_TYPE");
            String[] cofTypes = (String[]) coffeeTypes.getArray();

            Ref managerRef = rs.getRef("MGR");
            PreparedStatement pstmt = con.prepareStatement("SELECT MANAGER FROM MANAGERS WHERE OID = ?");
            pstmt.setRef(1, managerRef);
            ResultSet rs2 = pstmt.executeQuery();
            rs2.next();
            Struct manager = (Struct) rs2.getObject("MANAGER");
            Object[] manAttrs = manager.getAttributes();

            System.out.print(storeNo + "   ");
            System.out.print(locAttrs[0] + " " + locAttrs[1] + " " + locAttrs[2] + ", " + locAttrs[3] + "  "
                    + locAttrs[4] + " ");
            for (int i = 0; i < cofTypes.length; i++)
                System.out.print(cofTypes[i] + " ");
            System.out.println(manAttrs[1] + ", " + manAttrs[2]);

            rs2.close();
            pstmt.close();
        }

        rs.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: " + ex.getMessage());
        System.err.println("SQLState:  " + ex.getSQLState());
        System.err.println("Message:  " + ex.getMessage());
        System.err.println("Vendor:  " + ex.getErrorCode());
    }
}

From source file:DemoPreparedStatementSetBlob.java

public static void main(String[] args) throws Exception {
    Connection conn = null;//from ww w . j av a  2  s. c om
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    java.sql.Blob blob = null;
    try {
        conn = getConnection();
        // prepare blob object from an existing binary column
        pstmt = conn.prepareStatement("select photo from my_pictures where id = ?");
        pstmt.setString(1, "0001");
        rs = pstmt.executeQuery();
        rs.next();
        blob = rs.getBlob(1);

        // prepare SQL query for inserting a new row using setBlob()
        String query = "insert into blob_table(id, blob_column) values(?, ?)";
        // begin transaction
        conn.setAutoCommit(false);

        pstmt = conn.prepareStatement(query);
        pstmt.setString(1, "0002");
        pstmt.setBlob(2, blob);

        int rowCount = pstmt.executeUpdate();
        System.out.println("rowCount=" + rowCount);
        // end transaction
        conn.commit();
    } finally {
        rs.close();
        pstmt.close();
        conn.close();
    }
}