Example usage for java.sql Statement close

List of usage examples for java.sql Statement close

Introduction

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

Prototype

void close() throws SQLException;

Source Link

Document

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

Usage

From source file:Main.java

public static void main(String[] args) {
    Connection conn = null;/*from  w  w  w.  j  a va 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;/*  www .j av a  2  s  .com*/
    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 privileges = null;/* www .j a  va  2 s.c o  m*/
    DatabaseMetaData meta = conn.getMetaData();
    // The '_' character represents any single character.
    // The '%' character represents any sequence of zero
    // or more characters.
    privileges = meta.getTablePrivileges(conn.getCatalog(), "%", "survey");
    while (privileges.next()) {
        String catalog = privileges.getString("TABLE_CAT");
        String schema = privileges.getString("TABLE_SCHEM");
        String tableName = privileges.getString("TABLE_NAME");
        String privilege = privileges.getString("PRIVILEGE");
        String grantor = privileges.getString("GRANTOR");
        String grantee = privileges.getString("GRANTEE");
        String isGrantable = privileges.getString("IS_GRANTABLE");

        System.out.println("table name:" + tableName);
        System.out.println("catalog:" + catalog);
        System.out.println("schema:" + schema);
        System.out.println("privilege:" + privilege);
        System.out.println("grantor:" + grantor);
        System.out.println("isGrantable:" + isGrantable);
        System.out.println("grantee:" + grantee);
    }

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

From source file:InsertRow.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*from w  w  w  .  j  a v  a  2s .com*/
    Statement stmt;
    String query = "select COF_NAME, PRICE 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");

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");

        uprs.moveToInsertRow();

        uprs.updateString("COF_NAME", "Kona");
        uprs.updateInt("SUP_ID", 150);
        uprs.updateFloat("PRICE", 10.99f);
        uprs.updateInt("SALES", 0);
        uprs.updateInt("TOTAL", 0);

        uprs.insertRow();
        uprs.beforeFirst();

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

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

    DatabaseMetaData meta = conn.getMetaData();
    // The '_' character represents any single character.
    // The '%' character represents any sequence of zero
    // or more characters.
    ResultSet rs = meta.getBestRowIdentifier(conn.getCatalog(), null, "survey",
            DatabaseMetaData.bestRowTemporary, false);
    while (rs.next()) {

        short actualScope = rs.getShort("SCOPE");
        String columnName = rs.getString("COLUMN_NAME");
        int dataType = rs.getInt("DATA_TYPE");
        String typeName = rs.getString("TYPE_NAME");
        int columnSize = rs.getInt("COLUMN_SIZE");
        short decimalDigits = rs.getShort("DECIMAL_DIGITS");
        short pseudoColumn = rs.getShort("PSEUDO_COLUMN");

        System.out.println("tableName=survey");
        System.out.println("scope=" + actualScope);
        System.out.println("columnName=" + columnName);
        System.out.println("dataType=" + dataType);
        System.out.println("typeName" + typeName);
        System.out.println("columnSize" + columnSize);
        System.out.println("decimalDigits" + decimalDigits);
        System.out.println("pseudoColumn" + pseudoColumn);
    }//from   w  ww  .j a v  a2  s .c om

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

From source file:BatchUpdate.java

public static void main(String args[]) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;// w  w  w . ja v a  2  s .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(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        con.setAutoCommit(false);
        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();
        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("SQLException: " + b.getMessage());
        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] + " ");
        }

    } 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:jfutbol.com.jfutbol.GcmSender.java

public static void main(String[] args) {
    log.info("GCM - Sender running");
    do {//from  ww  w  .j  a  va 2 s.  c  o m

        Connection conn = null;
        Connection conn2 = null;
        Statement stmt = null;
        Statement stmt2 = 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);
            conn2 = DriverManager.getConnection(DB_URL, USER, PASS);
            // STEP 4: Execute a query
            // System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT userId FROM notifications WHERE sentByGCM=0 GROUP BY userId";
            ResultSet rs = stmt.executeQuery(sql);
            // STEP 5: Extract data from result set
            while (rs.next()) {
                log.info("Notification found");
                int userId = rs.getInt("userId");

                stmt2 = conn2.createStatement();
                String sql2;
                sql2 = "SELECT COUNT(id) notificationCounter FROM notifications WHERE status=0 AND userId="
                        + userId;
                ResultSet rs2 = stmt2.executeQuery(sql2);
                int notificationCounter = rs2.getInt("notificationCounter");
                rs2.close();
                stmt2.close();
                // Retrieve by column name

                // Display values
                // System.out.print("userId: " + userId);
                // System.out.print(", notificationCounter: " +
                // notificationCounter);
                SendNotification(userId, notificationCounter);
            }
            // STEP 6: Clean-up environment
            rs.close();
            stmt.close();
            conn.close();
            conn2.close();
        } catch (SQLException se) {
            // Handle errors for JDBC
            log.error(se.getMessage());
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException se2) {
                log.error(se2.getMessage());
            } // nothing we can do
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                log.error(se.getMessage());
                se.printStackTrace();
            } // end finally try
        } // end try
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    } while (1 != 0);
}

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 privileges = null;/*from ww w . j  a v  a  2  s.  c  om*/
    DatabaseMetaData meta = conn.getMetaData();
    // The '_' character represents any single character.
    // The '%' character represents any sequence of zero
    // or more characters.
    privileges = meta.getColumnPrivileges(conn.getCatalog(), null, "survey", "%");
    while (privileges.next()) {

        String catalog = privileges.getString("TABLE_CAT");
        String schema = privileges.getString("TABLE_SCHEM");
        String tableName = privileges.getString("TABLE_NAME");
        String dbColumn = privileges.getString("COLUMN_NAME");
        String privilege = privileges.getString("PRIVILEGE");
        String grantor = privileges.getString("GRANTOR");
        String grantee = privileges.getString("GRANTEE");
        String isGrantable = privileges.getString("IS_GRANTABLE");

        System.out.println("table name:" + tableName);
        System.out.println("catalog:" + catalog);
        System.out.println("column:" + dbColumn);
        System.out.println("schema:" + schema);
        System.out.println("privilege:" + privilege);
        System.out.println("grantor:" + grantor);
        System.out.println("isGrantable:" + isGrantable);
        System.out.println("grantee:" + grantee);
    }

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

From source file:BatchUpdate.java

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

    ResultSet rs = null;/*from  w  w  w  . ja  v a  2 s  .  co 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:ForeignKeysCoffees.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/* w w w  .  j a  va 2 s.  co  m*/
    String createString = "create table COFFEESFK " + "(COF_NAME varchar(32) NOT NULL, " + "SUP_ID int, "
            + "PRICE float, " + "SALES int, " + "TOTAL int, " + "primary key(COF_NAME), "
            + "foreign key(SUP_ID) references SUPPLIERSPK)";
    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();
        stmt.executeUpdate(createString);

        DatabaseMetaData dbmd = con.getMetaData();

        ResultSet rs = dbmd.getImportedKeys(null, null, "COFFEESFK");
        while (rs.next()) {
            String pkTable = rs.getString("PKTABLE_NAME");
            String pkColName = rs.getString("PKCOLUMN_NAME");
            String fkTable = rs.getString("FKTABLE_NAME");
            String fkColName = rs.getString("FKCOLUMN_NAME");
            short updateRule = rs.getShort("UPDATE_RULE");
            short deleteRule = rs.getShort("DELETE_RULE");
            System.out.println("primary key table name :  " + pkTable);
            System.out.print("primary key column name :  ");
            System.out.println(pkColName);
            System.out.println("foreign key table name :  " + fkTable);
            System.out.print("foreign key column name :  ");
            System.out.println(fkColName);
            System.out.println("update rule:  " + updateRule);
            System.out.println("delete rule:  " + deleteRule);
            System.out.println("");
        }

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

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