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

/**
 * Test Validity of a Connection/* www.java  2  s  . c o m*/
 * 
 * @param conn
 *          a JDBC connection object
 * @param query
 *          a sql query to test against db connection
 * @return true if a given connection object is a valid one; otherwise return
 *         false.
 */
public static boolean testConnection(Connection conn, String query) {
    ResultSet rs = null;
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        if (stmt == null) {
            return false;
        }

        rs = stmt.executeQuery(query);
        if (rs == null) {
            return false;
        }

        // connection object is valid: you were able to
        // connect to the database and return something useful.
        if (rs.next()) {
            return true;
        }

        // there is no hope any more for the validity
        // of the Connection object
        return false;
    } catch (Exception e) {
        // something went wrong: connection is bad
        return false;
    } finally {
        // close database resources
        try {
            rs.close();
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:CheckJDBCInstallation_MySQL.java

/**
 * Test Validity of a Connection//from   ww w.  j a  v a2s .c o m
 * 
 * @param conn
 *          a JDBC connection object
 * @param query
 *          a sql query to test against database connection
 * @return true if a given connection object is a valid one; otherwise return
 *         false.
 */
public static boolean testConnection(Connection conn, String query) {

    ResultSet rs = null;
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        if (stmt == null) {
            return false;
        }

        rs = stmt.executeQuery(query);
        if (rs == null) {
            return false;
        }

        if (rs.next()) {
            // connection object is valid: we were able to
            // connect to the database and return something useful.
            return true;
        }

        // there is no hope any more for the validity
        // of the connection object
        return false;

    } catch (Exception e) {
        //
        // something went wrong: connection is bad
        //
        return false;
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:model.SQLiteModel.java

public static void update(String query) {
    //query = StringEscapeUtils.escapeJavaScript(query);
    //System.out.println(query);
    Statement stmt = null;
    try {/* www. j a  va  2s .co m*/

        stmt = c.createStatement();
        if (stmt.executeUpdate(query) == 0) {
            writeLineToLog("Records created successfully");
        }

        stmt.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.out.println("Unsuccessful update query: " + query);
        writeLineToLog("Unsuccessful update query: " + query);
    }
}

From source file:com.srotya.tau.ui.Utils.java

public static void createDatabase(String dbConnectionString, String dbName, String user, String pass,
        String driver) throws Exception {
    Connection conn = null;/*from   www.jav  a  2 s.  com*/
    Statement stmt = null;
    try {
        // STEP 2: Register JDBC driver
        Class.forName(driver);

        // STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(dbConnectionString, user, pass);

        // STEP 4: Execute a query
        System.out.println("Creating database...");
        stmt = conn.createStatement();

        String sql = "CREATE DATABASE IF NOT EXISTS " + dbName;
        stmt.executeUpdate(sql);
        System.out.println("Database created successfully...");
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } // end finally try
    } // end try
}

From source file:net.tirasa.ilgrosso.resetdb.Main.java

private static void resetPostgreSQL(final Connection conn) throws Exception {

    final Statement statement = conn.createStatement();

    final ResultSet resultSet = statement
            .executeQuery("SELECT 'DROP TABLE ' || c.relname || ' CASCADE;' FROM pg_catalog.pg_class c "
                    + "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
                    + "WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') "
                    + "AND pg_catalog.pg_table_is_visible(c.oid)");
    final List<String> drops = new ArrayList<String>();
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }//from  w  w w  .j  a  v  a  2 s.co  m
    resultSet.close();

    for (String drop : drops) {
        statement.executeUpdate(drop.substring(0, drop.length() - 1));
    }

    statement.close();
    conn.close();
}

From source file:com.uber.hoodie.cli.utils.HiveUtil.java

public static long countRecords(String jdbcUrl, HoodieTableMetaClient source, String dbName, String user,
        String pass) throws SQLException {
    Connection conn = HiveUtil.getConnection(jdbcUrl, user, pass);
    ResultSet rs = null;//from   w ww .j  av a2 s  . c o  m
    Statement stmt = conn.createStatement();
    try {
        //stmt.execute("set mapred.job.queue.name=<queue_name>");
        stmt.execute("set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat");
        stmt.execute("set hive.stats.autogather=false");
        rs = stmt.executeQuery("select count(`_hoodie_commit_time`) as cnt from " + dbName + "."
                + source.getTableConfig().getTableName());
        long count = -1;
        if (rs.next()) {
            count = rs.getLong("cnt");
        }
        System.out.println("Total records in " + source.getTableConfig().getTableName() + " is " + count);
        return count;
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:ProxyAuthTest.java

private static void runQuery(String sqlStmt) throws Exception {
    Statement stmt = con.createStatement();
    ResultSet res = stmt.executeQuery(sqlStmt);

    ResultSetMetaData meta = res.getMetaData();
    System.out.println("Resultset has " + meta.getColumnCount() + " columns");
    for (int i = 1; i <= meta.getColumnCount(); i++) {
        System.out.println(/*w w  w . j a  v  a 2  s  . co  m*/
                "Column #" + i + " Name: " + meta.getColumnName(i) + " Type: " + meta.getColumnType(i));
    }

    while (res.next()) {
        for (int i = 1; i <= meta.getColumnCount(); i++) {
            System.out.println("Column #" + i + ": " + res.getString(i));
        }
    }
    res.close();
    stmt.close();
}

From source file:com.cloudera.sqoop.manager.SQLServerManagerExportManualTest.java

public static void checkSQLBinaryTableContent(String[] expected, String tableName, Connection connection) {
    Statement stmt = null;
    ResultSet rs = null;/* w ww  .  j  av a2 s .  co m*/
    try {
        stmt = connection.createStatement();
        rs = stmt.executeQuery("SELECT TOP 1 [b1], [b2] FROM " + tableName);
        rs.next();
        assertEquals(expected[0], rs.getString("b1"));
        assertEquals(expected[1], rs.getString("b2"));
    } catch (SQLException e) {
        LOG.error("Can't verify table content", e);
        fail();
    } finally {
        try {
            connection.commit();

            if (stmt != null) {
                stmt.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException ex) {
            LOG.info("Ignored exception in finally block.");
        }
    }
}

From source file:io.agi.framework.persistence.jdbc.JdbcUtil.java

/**
 * Execute an INSERT or UPDATE statement, that doesn't return any data.
 *
 * @param dbUrl/*from   w w w. j a  v  a  2 s  .  c o m*/
 * @param user
 * @param password
 * @param sql
 */
public static void Execute(String dbUrl, String user, String password, String sql) {
    Connection c = null;
    Statement s = null;
    try {
        c = DriverManager.getConnection(dbUrl, user, password);

        //STEP 4: Execute a query
        //_logger.info( "JDBC T: {} @1 jdbc = {}", System.currentTimeMillis(), sql );
        s = c.createStatement();
        //_logger.info( "JDBC T: {} @2 ", System.currentTimeMillis() );
        s.execute(sql);
        //_logger.info( "JDBC T: {} @3 ", System.currentTimeMillis() );

        //STEP 6: Clean-up environment
        //            s.close();
        //            c.close();
    } catch (SQLException se) {
        logger.error(se.toString(), se);
    } catch (Exception e) {
        logger.error(s.toString(), s);
    } finally {
        try {
            if (s != null)
                s.close();
        } catch (SQLException se2) {
            logger.error(se2.toString(), se2);
        } finally {
            try {
                if (c != null)
                    c.close();
            } catch (SQLException se) {
                logger.error(se.toString(), se);
            }
        }
    }
}

From source file:com.micromux.cassandra.jdbc.SpashScreenTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    // configure OPTIONS
    if (!StringUtils.isEmpty(TRUST_STORE)) {
        OPTIONS = String.format("trustStore=%s&trustPass=%s", URLEncoder.encode(TRUST_STORE), TRUST_PASS);
    }/*  w  w w  . j  av a  2s.c o m*/

    Class.forName("com.micromux.cassandra.jdbc.CassandraDriver");
    con = DriverManager.getConnection(
            String.format("jdbc:cassandra://%s:%d/%s?%s&version=3.0.0", HOST, PORT, "system", OPTIONS));
    Statement stmt = con.createStatement();

    // Drop Keyspace
    String dropKS = String.format("DROP KEYSPACE %s;", KEYSPACE);

    try {
        stmt.execute(dropKS);
    } catch (Exception e) {
        /* Exception on DROP is OK */}

    // Create KeySpace
    String createKS = String.format(
            "CREATE KEYSPACE \"%s\" WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};",
            KEYSPACE);
    stmt = con.createStatement();
    stmt.execute(createKS);

    // Use Keyspace
    String useKS = String.format("USE %s;", KEYSPACE);
    stmt.execute(useKS);

    // Create the target Column family
    String create = "CREATE COLUMNFAMILY Test (KEY text PRIMARY KEY, a bigint, b bigint) ;";
    stmt = con.createStatement();
    stmt.execute(create);
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));
}