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:dbservlet.Servlet.java

public void close(Statement stat, Connection conn) throws SQLException {
    if (stat != null) {
        stat.close();
    }//from ww  w .  ja v a  2s.c om
    if (conn != null) {
        conn.close();
    }

}

From source file:com.laudandjolynn.mytv.Main.java

/**
 * ???/*  w  w w  . j ava2 s. c  o  m*/
 */
private static void initDbData0(MyTvData data) {
    if (data.isDataInited()) {
        logger.info("init data had insert into db.");
        return;
    }
    Properties tvStationProp = new Properties();
    try {
        tvStationProp.load(Main.class.getResourceAsStream("/" + Constant.TV_STATION_INIT_DATA_FILE_NAME));
    } catch (IOException e) {
        throw new MyTvException(
                "error occur while load property file: " + Constant.TV_STATION_INIT_DATA_FILE_NAME, e);
    }

    Collection<Object> values = tvStationProp.values();
    List<String> insertSqlList = new ArrayList<String>(values.size());
    String insertSql = "insert into my_tv (stationName,displayName,classify,channel,sequence)";
    for (Object value : values) {
        insertSqlList.add(insertSql + " values (" + value.toString() + ")");
    }

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DataSourceManager.getConnection();
        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        for (String sql : insertSqlList) {
            stmt.addBatch(sql);
            logger.info("execute sql: " + sql);
        }
        stmt.executeBatch();
        conn.commit();
        data.writeData(null, Constant.XML_TAG_DATA, "true");
    } catch (SQLException e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new MyTvException("error occur while rollback transaction.", e1);
            }
        }
        throw new MyTvException("error occur while execute sql on db.", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new MyTvException("error occur while close statement.", e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new MyTvException("error occur while close sqlite connection.", e);
            }
        }
    }

}

From source file:com.gdo.project.util.SqlUtils.java

private static void closeStatement(StclContext stclContext, Statement stmt) {
    try {//from   ww w  .j  a  v a2  s  .c  om
        if (stmt != null) {
            stmt.close();
        }
    } catch (SQLException e) {
        logWarn(stclContext, e.toString());
    }
}

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

private void tryAndCloseConnection(Connection connection) throws Exception {
    Statement stmt = connection.createStatement();
    stmt.execute("select 1 from dual");
    ResultSet result = stmt.getResultSet();
    result.next();/*from w  w  w. j a  v a 2  s  .c  o m*/
    assertEquals(1, result.getInt(1));
    result.close();
    stmt.close();
    connection.close();
}

From source file:be.fedict.eid.integration.setup.db.SetupDatabase.java

@BeforeSuite
@Parameters("context")
public void setupDatabase(String context) throws ClassNotFoundException, SQLException, IOException {
    try {// w  w  w.jav a2 s.  co  m
        // Setup the database
        loadJdbcDriver();

        // Get a connection
        Connection connection = openConnection();

        // Execute the update
        try {
            Statement statement = connection.createStatement();

            try {
                String sql = readSql(context);
                statement.execute(sql);
            } finally {
                statement.close();
            }

        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:com.bt.aloha.testing.DbTestCase.java

protected synchronized String query(String expression) throws SQLException {
    Statement st = connection.createStatement();
    try {// w ww .j a  va 2s. co m
        ResultSet rs = st.executeQuery(expression);
        return dump(rs);
    } finally {
        st.close();
    }
}

From source file:ems.util.DataHandler.java

public static List<MyModel> getDashboardData(String reportType) {
    List<MyModel> myModels = new LinkedList<>();
    String sqlQuery = "";
    switch (reportType) {
    case "1":
        sqlQuery = Q_S_DASHBOARD_CAST_WISE;
        break;/*from   w  ww . ja v  a2s.co  m*/
    case "2":
        sqlQuery = Q_S_DASHBOARD_GENDER_WISE;
        break;
    case "3":
        sqlQuery = Q_S_DASHBOARD_COLOR_WISE;
        break;
    }
    Connection con = getConnection();
    Statement s = null;
    ResultSet rs = null;
    try {
        s = con.createStatement();
        rs = s.executeQuery(sqlQuery);
        while (rs.next()) {
            myModels.add(new MyModel(rs.getString(1), rs.getString(2)));
        }
    } catch (Exception e) {
        log.error("getDashboardData: " + e.getMessage());
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (s != null) {
                s.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException ex) {
            log.error("getDashboardData: " + ex.getMessage());
        }
    }
    return myModels;
}

From source file:database.HashTablesTools.java

public static int countFilesWhichAreAlreadyIndexedInSequenceDB_notgood_either(String tableName,
        String tableFailureName, Map<String, List<MMcifFileInfos>> indexPDBFileInFolder) {

    Connection connection = HashTablesTools.getConnection(tableName, tableFailureName);

    int countOfHashFoundInFailureDB = 0;
    int countOfHashFoundInSequenceDB = 0;
    // fastest/* ww  w. java2 s  .c  o m*/
    Statement stmt = null;
    ResultSet resultFindEntryFailureDb = null;
    for (Map.Entry<String, List<MMcifFileInfos>> entry : indexPDBFileInFolder.entrySet()) {
        A: for (MMcifFileInfos fileInfos : entry.getValue()) {

            try {
                stmt = connection.createStatement();
                String findEntry = "SELECT * from " + tableFailureName + " WHERE pdbfilehash = '"
                        + fileInfos.getHash() + "'";
                resultFindEntryFailureDb = stmt.executeQuery(findEntry);

                if (resultFindEntryFailureDb.next()) {
                    countOfHashFoundInFailureDB += 1;
                    stmt.close();
                    continue A;

                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            // if here not found in failureDB
            try {
                stmt = connection.createStatement();
                String findEntry = "SELECT * from " + tableName + " WHERE pdbfilehash = '" + fileInfos.getHash()
                        + "'";
                resultFindEntryFailureDb = stmt.executeQuery(findEntry);

                if (resultFindEntryFailureDb.next()) {
                    countOfHashFoundInSequenceDB += 1;
                    stmt.close();
                    continue A;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    HashTablesTools.shutdown();
    return countOfHashFoundInFailureDB + countOfHashFoundInSequenceDB;
}

From source file:com.p6spy.engine.spy.DataSourceTest.java

@Test
public void testGenericDataSourceWithDriverManager() throws Exception {
    // Create and bind the real data source
    // Note: This will get the driver from the DriverManager
    realDs = new TestBasicDataSource();
    realDs.setDriverClassName(driverClass);
    realDs.setUrl(url);/*from   w ww  .ja va 2s.  c  om*/
    realDs.setUsername(user);
    realDs.setPassword(password);
    realDs.setUseDriverManager(true);
    realDsResource = new Resource("jdbc/realDs", realDs);

    P6TestUtil.setupTestData(realDs);

    // get the data source from JNDI
    DataSource ds = new JndiDataSourceLookup().getDataSource("jdbc/spyDs");
    assertNotNull("JNDI data source not found", ds);

    // get the connection
    con = ds.getConnection();

    // verify that the connection class is a proxy
    assertTrue("Connection is not a proxy", ProxyFactory.isProxy(con));

    Statement stmt = con.createStatement();
    stmt.execute("select 1 from customers");
    stmt.close();
    assertTrue(((P6TestLogger) P6LogQuery.getLogger()).getLastEntry().indexOf("select 1") != -1);
    assertEquals("Incorrect number of spy log messages", 1,
            ((P6TestLogger) P6LogQuery.getLogger()).getLogs().size());
}

From source file:de.langmi.spring.batch.examples.readers.jdbc.JdbcPagingItemReaderTests.java

/**
 * Setup Datasource and create table for test.
 *
 * @throws Exception /*from   w w w  .  ja v a 2  s. c  o m*/
 */
@Before
public void setUp() throws Exception {
    // DataSource Setup, apache commons 
    dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    dataSource.setUrl("jdbc:hsqldb:mem:testdb");
    dataSource.setUsername("sa");
    dataSource.setPassword("");

    // drop table if exists
    Connection conn = dataSource.getConnection();
    Statement st = conn.createStatement();
    st.execute(DROP_TEST_TABLE);
    conn.commit();
    st.close();
    conn.close();

    // create table
    conn = dataSource.getConnection();
    st = conn.createStatement();
    st.execute(CREATE_TEST_TABLE);
    conn.commit();
    st.close();
    conn.close();

    // fill with values
    conn = dataSource.getConnection();
    // prevent auto commit for batching
    conn.setAutoCommit(false);
    PreparedStatement ps = conn.prepareStatement(INSERT);
    // fill with values
    for (int i = 0; i < EXPECTED_COUNT; i++) {
        ps.setString(1, String.valueOf(i));
        ps.addBatch();
    }
    ps.executeBatch();
    conn.commit();
    ps.close();
    conn.close();
}