Example usage for java.sql Statement executeQuery

List of usage examples for java.sql Statement executeQuery

Introduction

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

Prototype

ResultSet executeQuery(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which returns a single ResultSet object.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("create table survey (id int, id2 tinyint, id3 smallint, id4 bigint, id5 real);");
    String sql = "INSERT INTO survey (id2,id3,id4,id5) VALUES(?,?,?,?)";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    byte b = 1;/*from w  ww. j a v  a 2 s.  co m*/
    short s = 2;
    pstmt.setByte(1, b);
    pstmt.setShort(2, s);
    pstmt.setInt(3, 3);
    pstmt.setLong(4, 4L);
    pstmt.executeUpdate();

    ResultSet rs = stmt.executeQuery("SELECT * FROM survey");
    while (rs.next()) {
        System.out.println(rs.getString(2));
    }
    rs.close();
    stmt.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 forward
    while (rs.next()) {
        // Get data at cursor
        String id = rs.getString(1);
        String name = rs.getString(2);
    }/* ww w .  ja  v  a  2 s . c o m*/

    // Move cursor backward
    while (rs.previous()) {
        // Get data at cursor
        String id = rs.getString(1);
        String name = rs.getString(2);
    }

    // Move cursor to the first row
    rs.first();

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

    // Move cursor to the end, after the last row
    rs.afterLast();

    // Move cursor to the beginning, before the first row.
    // cursor position is 0.
    rs.beforeFirst();

    // Move cursor to the second row
    rs.absolute(2);

    // Move cursor to the last row
    rs.absolute(-1);

    // Move cursor to the second-to-last row
    rs.absolute(-2);

    // Move cursor down 5 rows from the current row. If this moves
    // cursor beyond the last row, cursor is put after the last row
    rs.relative(5);

    // Move cursor up 3 rows from the current row. If this moves
    // cursor beyond the first row, cursor is put before the first row
    rs.relative(-3);

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

}

From source file:RSMetaDataMethods.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//from w ww.j  av  a 2  s  . c  om
    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("select * from COFFEES");
        ResultSetMetaData rsmd = rs.getMetaData();

        int numberOfColumns = rsmd.getColumnCount();
        for (int i = 1; i <= numberOfColumns; i++) {
            String colName = rsmd.getColumnName(i);
            String tableName = rsmd.getTableName(i);
            String name = rsmd.getColumnTypeName(i);
            boolean caseSen = rsmd.isCaseSensitive(i);
            boolean writable = rsmd.isWritable(i);
            System.out.println("Information for column " + colName);
            System.out.println("    Column is in table " + tableName);
            System.out.println("    DBMS name for type is " + name);
            System.out.println("    Is case sensitive:  " + caseSen);
            System.out.println("    Is possibly writable:  " + writable);
            System.out.println("");
        }

        while (rs.next()) {
            for (int i = 1; i <= numberOfColumns; i++) {
                String s = rs.getString(i);
                System.out.print(s + "  ");
            }
            System.out.println("");
        }

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

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

From source file:InsertRowBug.java

public static void main(String args[]) {

    String url;//from  w  w w  .j a va 2 s. c o m
    // url = "jdbc:odbc:SQL Anywhere 5.0 Sample";
    // url = "jdbc:oracle:thin:@server:1521:db570";
    url = "jdbc:odbc:RainForestDSN";

    String driver;
    //driver = "oracle.jdbc.driver.OracleDriver";
    driver = "sun.jdbc.odbc.JdbcOdbcDriver";

    String user, pass;
    user = "student";
    pass = "student";

    Connection con;
    Statement stmt;
    ResultSet uprs;

    try {
        Class.forName(driver);

    } catch (java.lang.ClassNotFoundException e) {
        System.err.println(e);
        return;
    }

    try {
        con = DriverManager.getConnection(url, user, pass);
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        uprs = stmt.executeQuery("SELECT * FROM Music_Recordings");

        // Check the column count
        ResultSetMetaData md = uprs.getMetaData();
        System.out.println("Resultset has " + md.getColumnCount() + " cols.");

        int rowNum = uprs.getRow();
        System.out.println("row1 " + rowNum);
        uprs.absolute(1);
        rowNum = uprs.getRow();
        System.out.println("row2 " + rowNum);
        uprs.next();
        uprs.moveToInsertRow();
        uprs.updateInt(1, 150);
        uprs.updateString(2, "Madonna");
        uprs.updateString(3, "Dummy");
        uprs.updateString(4, "Jazz");
        uprs.updateString(5, "Image");
        uprs.updateInt(6, 5);
        uprs.updateDouble(7, 5);
        uprs.updateInt(8, 15);
        uprs.insertRow();
        uprs.close();
        stmt.close();
        con.close();
    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:Main.java

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

    st.executeUpdate("create table survey (id int,myDate TIMESTAMP );");
    String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";

    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
    pstmt.setString(1, "1");
    java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
    pstmt.setTimestamp(2, sqlDate);// w w w . j av  a2 s .  c om

    pstmt.executeUpdate();

    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    outputResultSet(rs);

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

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement stmt = conn.createStatement();

    stmt.executeUpdate("create table survey (id int, id2 tinyint, id3 smallint, id4 bigint, id5 real);");

    String sql = "INSERT INTO survey (id2,id3,id4,id5) VALUES(?,?,?,?)";
    PreparedStatement pstmt = conn.prepareStatement(sql);

    byte b = 1;// www  .jav  a2 s  . com
    short s = 2;
    pstmt.setByte(1, b);
    pstmt.setShort(2, s);
    pstmt.setInt(3, 3);
    pstmt.setLong(4, 4L);
    pstmt.executeUpdate();

    ResultSet rs = stmt.executeQuery("SELECT * FROM survey");
    while (rs.next()) {
        System.out.println(rs.getString(2));
    }

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

From source file:PrintColumns.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*  w w  w.j a va 2s  .co m*/
    String query = "select * from COFFEES";
    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();

        PrintColumnTypes.printColTypes(rsmd);
        System.out.println("");

        int numberOfColumns = rsmd.getColumnCount();

        for (int i = 1; i <= numberOfColumns; i++) {
            if (i > 1)
                System.out.print(",  ");
            String columnName = rsmd.getColumnName(i);
            System.out.print(columnName);
        }
        System.out.println("");

        while (rs.next()) {
            for (int i = 1; i <= numberOfColumns; i++) {
                if (i > 1)
                    System.out.print(",  ");
                String columnValue = rs.getString(i);
                System.out.print(columnValue);
            }
            System.out.println("");
        }

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

From source file:com.jt.dbcp.example.BasicDataSourceExample.java

public static void main(String[] args) {
    // First we set up the BasicDataSource.
    // Normally this would be handled auto-magically by
    // an external configuration, but in this example we'll
    // do it manually.
    ///*from  ww w  .  j a  v  a2s .c  o  m*/
    String param1 = null;
    String param2 = null;
    if (args.length == 2) {
        param1 = args[0];
        param2 = args[1];
    }

    if (param1 == null) {
        param1 = "jdbc:mysql://localhost:3306/test";
        param2 = "select * from t_user";
    }
    System.out.println("Setting up data source.");
    DataSource dataSource = setupDataSource(param1);
    System.out.println("Done.");

    //
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(param2);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        int count = 0;
        while (rset.next()) {
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
            count++;
            if (count == 10) {
                break;
            }
        }
        printDataSourceStats(dataSource);

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rset != null)
                rset.close();
        } catch (Exception e) {
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
        try {
            shutdownDataSource(dataSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:Commons.dbcp.ManualPoolingDataSourceExample.java

public static void main(String[] args) {
    ////  w w  w  .  ja va  2  s  .co m
    // First we load the underlying JDBC driver.
    // You need this if you don't use the jdbc.drivers
    // system property.
    //
    System.out.println("Loading underlying JDBC driver.");
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("Done.");

    //
    // Then, we set up the PoolingDataSource.
    // Normally this would be handled auto-magically by
    // an external configuration, but in this example we'll
    // do it manually.
    //
    System.out.println("Setting up data source.");
    ////ee  DataSource dataSource = setupDataSource(args[0]);
    DataSource dataSource = setupDataSource("jdbc:oracle:thin:@10.1.1.184:1521:UTF8");
    System.out.println("Done.");

    //
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(args[1]);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        while (rset.next()) {
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            rset.close();
        } catch (Exception e) {
        }
        try {
            stmt.close();
        } catch (Exception e) {
        }
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:PoolingDataSourceExample.java

public static void main(String[] args) {
    ///*from   w  w w . j  a  v a 2 s.c  om*/
    // First we load the underlying JDBC driver.
    // You need this if you don't use the jdbc.drivers
    // system property.
    //
    System.out.println("Loading underlying JDBC driver.");
    try {
        Class.forName("org.h2.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("Done.");

    //
    // Then, we set up the PoolingDataSource.
    // Normally this would be handled auto-magically by
    // an external configuration, but in this example we'll
    // do it manually.
    //
    System.out.println("Setting up data source.");
    DataSource dataSource = setupDataSource(args[0]);
    System.out.println("Done.");

    //
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(args[1]);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        while (rset.next()) {
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rset != null)
                rset.close();
        } catch (Exception e) {
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}