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:com.ubipass.middleware.ems.EMSUtil.java

/**
 * Get last time of system shutdown./*from  www .  jav  a  2 s . c  o m*/
 * 
 * @return time stamp of last system shutdown
 */
private static long getLastShutdownTime() {

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    long result = 0;

    try {
        conn = DBConnPool.getConnection();

        // get last shutdown time from table sysconfig
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT currentTime FROM sysconfig");
        rs.next();
        result = rs.getLong(1);
    } catch (Exception e) {
        SystemLogger.error("[EMS] getLastShutdownTime() error: " + e.getMessage());
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }

            if (stmt != null) {
                stmt.close();
            }

            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {

        }
    }

    return (result == 0) ? new Date().getTime() : result;

}

From source file:com.baidu.qa.service.test.util.JdbcUtil.java

protected static void excuteVerifyDeleteSqls(List<String> sqlStrs, String dbname) throws Exception {

    Connection con = null;// w ww .  j  a v  a 2  s .  co  m
    Statement sm = null;
    ResultSet rs = null;
    try {
        //?
        con = MysqlDatabaseManager.getCon(dbname);
        Assert.assertNotNull("connect to db error:" + dbname, con);

        //??
        sm = con.createStatement();
        for (String sqlStr : sqlStrs) {
            rs = sm.executeQuery(sqlStr);
            log.info("[sql:]" + sqlStr);

            Assert.assertFalse("[db expect error],has data like:" + sqlStr, rs.next());
            rs.close();
        }

    } catch (Exception e) {

        throw e;
    } finally {
        if (con != null) {
            con.close();
        }
        if (sm != null) {
            sm.close();
        }
        if (rs != null) {
            rs.close();
        }
    }

}

From source file:com.baidu.qa.service.test.util.JdbcUtil.java

protected static void excuteVerifySqls(List<String> sqlStrs, String dbname) throws Exception {

    //   ???//from   w ww. jav  a2 s  . com
    Connection con = null;
    Statement sm = null;
    ResultSet rs = null;
    try {
        //?
        con = MysqlDatabaseManager.getCon(dbname);
        Assert.assertNotNull("connect to db error:" + dbname, con);

        //??
        sm = con.createStatement();
        for (String sqlStr : sqlStrs) {
            rs = sm.executeQuery(sqlStr);
            log.info("[sql:]" + sqlStr);

            Assert.assertTrue("[db expect error],has no data like:" + sqlStr, rs.next());
            rs.close();
        }

    } catch (Exception e) {
        throw e;
    } finally {
        if (con != null) {
            con.close();
        }
        if (sm != null) {
            sm.close();
        }
        if (rs != null) {
            rs.close();
        }

    }

}

From source file:com.espertech.esper.epl.db.DatabasePollingViewableFactory.java

private static QueryMetaData getExampleQueryMetaData(Connection connection, String[] parameters,
        String sampleSQL, ColumnSettings metadataSetting, boolean isUsingMetadataSQL)
        throws ExprValidationException {
    // Simply add up all input parameters
    List<String> inputParameters = new LinkedList<String>();
    inputParameters.addAll(Arrays.asList(parameters));

    Statement statement;
    try {/*from   ww w.j a  v  a2 s.  com*/
        statement = connection.createStatement();
    } catch (SQLException ex) {
        String text = "Error creating statement";
        log.error(text, ex);
        throw new ExprValidationException(text + ", reason: " + ex.getMessage());
    }

    ResultSet result = null;
    try {
        result = statement.executeQuery(sampleSQL);
    } catch (SQLException ex) {
        try {
            statement.close();
        } catch (SQLException e) {
            log.info("Error closing statement: " + e.getMessage(), e);
        }

        String text;
        if (isUsingMetadataSQL) {
            text = "Error compiling metadata SQL to retrieve statement metadata, using sql text '" + sampleSQL
                    + "'";
        } else {
            text = "Error compiling metadata SQL to retrieve statement metadata, consider using the 'metadatasql' syntax, using sql text '"
                    + sampleSQL + "'";
        }

        log.error(text, ex);
        throw new ExprValidationException(text + ", reason: " + ex.getMessage());
    }

    Map<String, DBOutputTypeDesc> outputProperties;
    try {
        outputProperties = compileResultMetaData(result.getMetaData(), metadataSetting);
    } catch (SQLException ex) {
        try {
            result.close();
        } catch (SQLException e) {
            // don't handle
        }
        try {
            statement.close();
        } catch (SQLException e) {
            // don't handle
        }
        String text = "Error in statement '" + sampleSQL + "', failed to obtain result metadata";
        log.error(text, ex);
        throw new ExprValidationException(text + ", please check the statement, reason: " + ex.getMessage());
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                log.warn("Exception closing result set: " + e.getMessage());
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                log.warn("Exception closing result set: " + e.getMessage());
            }
        }
    }

    return new QueryMetaData(inputParameters, outputProperties);
}

From source file:com.aurel.track.dbase.UpdateDbSchema.java

private static boolean hasTables(Connection conn) {
    boolean hasTables = false;
    try {//from ww  w  .j a v  a 2s.  c om
        DatabaseMetaData md = conn.getMetaData();
        String userName = md.getUserName();
        String url = md.getURL();
        boolean isOracleOrDb2 = url.startsWith("jdbc:oracle") || url.startsWith("jdbc:db2");
        ResultSet rsTables = md.getTables(conn.getCatalog(), isOracleOrDb2 ? userName : null, null, null);
        LOGGER.info("Getting the tables metadata");
        if (rsTables != null && rsTables.next()) {
            LOGGER.info("Find TSITE table...");

            while (rsTables.next()) {
                String tableName = rsTables.getString("TABLE_NAME");
                String tablenameUpperCase = tableName.toUpperCase();
                if ("TSITE".equals(tablenameUpperCase)) {
                    LOGGER.info("TSITE table found");
                    hasTables = true;
                    break;
                } else {
                    if (tablenameUpperCase.endsWith("TSITE")) {
                        LOGGER.info(tablenameUpperCase + " table found");
                        hasTables = true;
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (!hasTables) {
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT OBJECTID FROM TSITE");
            if (rs.next()) {
                hasTables = true;
            }
        } catch (SQLException e) {
            LOGGER.info("Table TSITE  does not exist");
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                }
            }
        }
    }
    return hasTables;
}

From source file:de.unibi.cebitec.bibiserv.util.visualizer.AbstractTest.java

private static DataSource derbydb() throws Exception {

    EmbeddedDataSource ds = new EmbeddedDataSource();

    String db = "test/testdb_" + System.currentTimeMillis();

    // check if database exists
    File db_dir = new File(db);
    if (db_dir.exists()) {
        try {//www .  j a  va2 s . co m
            FileUtils.deleteDirectory(db_dir);
        } catch (IOException e) {
            LOG.error(e);
            assertTrue(e.getMessage(), false);
        }
    }
    ds.setDatabaseName(db);
    ds.setCreateDatabase("create");

    Connection con = ds.getConnection();
    Statement stmt = con.createStatement();

    // read SQL Statement from file
    BufferedReader r = new BufferedReader(
            new InputStreamReader(TestRAEDA.class.getResourceAsStream("/status.sql")));
    String line;
    StringBuilder sql = new StringBuilder();
    while ((line = r.readLine()) != null) {
        // skip commend lines
        if (!line.startsWith("--")) {
            sql.append(line);
            sql.append('\n');
        }
    }
    r.close();

    // execute sqlcmd's
    for (String sqlcmd : sql.toString().split(";")) {
        sqlcmd = sqlcmd.trim(); // ignore trailing/ending whitespaces
        sqlcmd = sqlcmd.replaceAll("\n\n", "\n"); // remove double newline
        if (sqlcmd.length() > 1) { // if string contains more than one char, execute sql cmd
            LOG.debug(sqlcmd + "\n");
            stmt.execute(sqlcmd);
        }
    }

    // close stmt
    stmt.close();

    return ds;
}

From source file:name.livitski.tools.persista.StatementHandler.java

protected void close(Statement stmt) throws SQLException {
    stmt.close();
}

From source file:database.HashTablesTools.java

public static void createTables(Connection connection, String tableName, String tableFailureName) {

    dropTable(connection, tableName);// w w  w  .  ja v  a2s  .  c  o  m
    dropTable(connection, tableFailureName);

    // check if table exists if not create it
    // E95A91AD32BBFB2C7ACCC5E75F48686F
    try {
        Statement stmt = connection.createStatement();
        String createTableSql = "CREATE TABLE " + tableName
                + " (pdbfilehash varchar(32), fourLettercode varchar(4), chainId varchar(2), chainType varchar(2), sequenceString varchar("
                + maxCharInVarchar + "), PRIMARY KEY (pdbfilehash, chainId) ) ";
        System.out.println(createTableSql);
        stmt.executeUpdate(createTableSql);
        System.out.println("created table " + tableName + " in myDB !");
        stmt.close();
    } catch (SQLException e1) {
        System.out.println("Table " + tableName + " already exists in myDB !");
    }
    try {
        Statement stmt = connection.createStatement();
        String createTableSql = "CREATE TABLE " + tableFailureName
                + " (pdbfilehash varchar(32), fourLettercode varchar(4), PRIMARY KEY (pdbfilehash) ) ";
        System.out.println(createTableSql);
        stmt.executeUpdate(createTableSql);
        System.out.println("created table " + tableName + " in myDB !");
        stmt.close();
    } catch (SQLException e1) {
        System.out.println("Table " + tableName + " already exists in myDB !");
    }
}

From source file:com.edgenius.wiki.installation.ConnectionProxy.java

/**
 * @param sql/*from   ww  w .  jav a  2 s .c om*/
 * @return
 * @throws SQLException 
 */
public PreparedStatement prepareStatement(String sql) throws SQLException {
    //this is only for change schema
    if (!StringUtils.isBlank(schema)) {
        Statement stat = createStatement();
        stat.close();
    }
    PreparedStatement prepStat = conn.prepareStatement(sql);

    return prepStat;

}

From source file:com.oracle.tutorial.jdbc.CoffeesTable.java

public static void alternateViewTable(Connection con) throws SQLException {
    Statement stmt = null;
    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";
    try {/*from   www  .  j av  a 2 s.c om*/
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String coffeeName = rs.getString(1);
            int supplierID = rs.getInt(2);
            float price = rs.getFloat(3);
            int sales = rs.getInt(4);
            int total = rs.getInt(5);
            System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total);
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}