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 = null;/* ww  w.  j a va 2s  .co m*/
    PreparedStatement pstmt = null;
    Statement stmt = null;
    ResultSet rs = null;
    Class.forName(JDBC_DRIVER);
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    stmt = conn.createStatement();
    createXMLTable(stmt);
    File f = new File("build.xml");
    long fileLength = f.length();
    FileInputStream fis = new FileInputStream(f);
    String SQL = "INSERT INTO XML_Data VALUES (?,?)";
    pstmt = conn.prepareStatement(SQL);
    pstmt.setInt(1, 100);
    pstmt.setAsciiStream(2, fis, (int) fileLength);
    pstmt.execute();
    fis.close();
    SQL = "SELECT Data FROM XML_Data WHERE id=100";
    rs = stmt.executeQuery(SQL);
    if (rs.next()) {
        InputStream xmlInputStream = rs.getAsciiStream(1);
        int c;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((c = xmlInputStream.read()) != -1)
            bos.write(c);
        System.out.println(bos.toString());
    }
    rs.close();
    stmt.close();
    pstmt.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("org.sqlite.JDBC");

    Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");

    Statement stat = conn.createStatement();
    stat.executeUpdate("drop table if exists people;");
    stat.executeUpdate("create table people (name, occupation);");
    PreparedStatement prep = conn.prepareStatement("insert into people values (?, ?);");

    prep.setString(1, "G");
    prep.setString(2, "politics");
    prep.addBatch();//from w ww  . ja  v  a2 s .c  o  m
    prep.setString(1, "Turing");
    prep.setString(2, "computers");
    prep.addBatch();
    prep.setString(1, "W");
    prep.setString(2, "Tester");
    prep.addBatch();

    conn.setAutoCommit(false);
    prep.executeBatch();
    conn.setAutoCommit(true);

    ResultSet rs = stat.executeQuery("select * from people;");
    while (rs.next()) {
        System.out.println("name = " + rs.getString("name"));
        System.out.println("job = " + rs.getString("occupation"));
    }
    rs.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    conn.setAutoCommit(false);//from ww w  . j a v  a 2s  .  co  m
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int, name VARCHAR(30) );");

    String INSERT_RECORD = "insert into survey(id, name) values(?,?)";

    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
    pstmt.setString(1, "1");
    pstmt.setString(2, "name1");
    pstmt.addBatch();

    pstmt.setString(1, "2");
    pstmt.setString(2, "name2");
    pstmt.addBatch();

    // execute the batch
    int[] updateCounts = pstmt.executeBatch();

    checkUpdateCounts(updateCounts);

    // since there were no errors, commit
    conn.commit();

    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();
    conn.setAutoCommit(false);/* ww  w .j a v  a2 s . c om*/
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int, name VARCHAR(30) );");
    st.addBatch("DELETE FROM survey");

    st.addBatch("INSERT INTO survey(id, name) " + "VALUES(444, 'ginger')");
    // we intentionally pass a table name (animals_tableZZ)
    // that does not exist
    st.addBatch("INSERT INTO survey(id, name) " + "VALUES(555, 'lola')");
    st.addBatch("INSERT INTO survey(id, name) " + "VALUES(666, 'freddy')");

    // Execute the batch
    int[] updateCounts = st.executeBatch();

    checkUpdateCounts(updateCounts);

    // since there were no errors, commit
    conn.commit();

    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 {
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";

    Connection con;/*from w  ww. ja  v a2 s  .  c  o m*/
    Statement stmt;
    ResultSet rs;

    try {
        Class.forName(driver);
        con = DriverManager.getConnection("jdbc:odbc:databaseName", "student", "student");
        // Start a transaction
        con.setAutoCommit(false);

        stmt = con.createStatement();
        stmt.addBatch("UPDATE EMP SET JOB = 1");

        // Submit the batch of commands for this statement to the database
        stmt.executeBatch();

        // Commit the transaction
        con.commit();

        // Close the existing to be safe before opening a new one
        stmt.close();

        // Print out the Employees
        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT * FROM EMP");
        // Loop through and print the employee number, job, and hiredate
        while (rs.next()) {
            int id = rs.getInt("EMPNO");
            int job = rs.getInt("JOB");
            String hireDate = rs.getString("HIREDATE");

            System.out.println(id + ":" + job + ":" + hireDate);
        }
        con.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "yourName", "mypwd");
    Statement stmt = conn.createStatement();

    String streamingDataSql = "CREATE TABLE XML_Data (id INTEGER, Data LONG)";
    try {//w  w  w  . j av  a  2 s.  c om
        stmt.executeUpdate("DROP TABLE XML_Data");
    } catch (SQLException se) {
        if (se.getErrorCode() == 942)
            System.out.println("Error dropping XML_Data table:" + se.getMessage());
    }
    stmt.executeUpdate(streamingDataSql);

    File f = new File("employee.xml");
    long fileLength = f.length();
    FileInputStream fis = new FileInputStream(f);
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO XML_Data VALUES (?,?)");
    pstmt.setInt(1, 100);
    pstmt.setAsciiStream(2, fis, (int) fileLength);
    pstmt.execute();
    fis.close();
    ResultSet rset = stmt.executeQuery("SELECT Data FROM XML_Data WHERE id=100");
    if (rset.next()) {
        InputStream xmlInputStream = rset.getAsciiStream(1);
        int c;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((c = xmlInputStream.read()) != -1)
            bos.write(c);
        System.out.println(bos.toString());
    }
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    conn.setAutoCommit(false);/*from ww w. j  av a2  s  .  c om*/
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int, name VARCHAR(30) );");

    String INSERT_RECORD = "insert into survey(id, name) values(?,?)";

    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);

    pstmt.setInt(1, 1);
    pstmt.setString(2, "name");
    pstmt.executeUpdate();

    // Get warnings on PreparedStatement object
    SQLWarning warning = pstmt.getWarnings();
    while (warning != null) {
        // Process statement warnings...
        String message = warning.getMessage();
        String sqlState = warning.getSQLState();
        int errorCode = warning.getErrorCode();
        warning = warning.getNextWarning();
    }

    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) {
    Connection conn = null;//from   w w  w  .jav  a 2 s  .c o m
    Statement stmt = null;
    try {
        // Register JDBC driver
        Class.forName(JDBC_DRIVER);

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

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

        // 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);
        }
        // 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) {
    Connection conn = null;/*  w  w  w  . j  av  a2s  . co 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:fr.eo.util.dumper.Dumper.java

/**
 * @param args/*from   w  w w .  j  a v  a  2s.com*/
 */
public static void main(String[] args) {

    String appName = args[0];

    System.out.println("Starting dumper ...");

    Statement stmt = null;

    try {
        System.out.println("Getting database connection ...");
        Connection conn = getJtdsConnection();

        List<RequestDefinitionBean> requests = RequestDefinitionParser.getRequests(appName);

        assetFolder = RequestDefinitionParser.getAppBaseDir(appName) + "assets/";

        for (RequestDefinitionBean request : requests) {
            int currentFileSize = 0, cpt = 1;
            stmt = conn.createStatement();
            System.out.println("Dumping " + request.name + "...");
            ResultSet rs = stmt.executeQuery(request.sql);
            BufferedWriter bw = getWriter(request.name, cpt);
            bw.append(COPYRIGHTS);
            currentFileSize += COPYRIGHTS.length();
            bw.append("--" + request.name + "\n");
            while (rs.next()) {
                StringBuilder sb = new StringBuilder();
                sb.append("INSERT INTO ");
                sb.append(request.table).append(" VALUES (");
                int pos = 0;
                for (String fieldName : request.fields) {
                    String str = getFieldValue(request, pos, rs, fieldName);
                    sb.append(str);
                    pos++;
                    if (pos < request.fields.size()) {
                        sb.append(",");
                    }
                }
                sb.append(");\n");
                currentFileSize += sb.length();
                bw.append(sb.toString());
                bw.flush();

                if (currentFileSize > MAX_FILE_SIZE) {
                    bw.close();

                    bw = getWriter(request.name, ++cpt);
                    bw.append(COPYRIGHTS);
                    bw.append("--" + request.name + "\n");
                    currentFileSize = COPYRIGHTS.length();
                }
            }
            bw.flush();
            bw.close();
        }

        System.out.println("done.");

    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    DumpFilesDescriptor descriptor = new DumpFilesDescriptor();
    descriptor.lineNumbers = getDumpLinesNumber();
    descriptor.dumpFileNames = dumpFileNames;
    writeDescriptorFile(descriptor);

    System.out.println("nb :" + descriptor.lineNumbers);
}