Example usage for java.sql PreparedStatement close

List of usage examples for java.sql PreparedStatement close

Introduction

In this page you can find the example usage for java.sql PreparedStatement 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.l2jfree.gameserver.datatables.HennaTable.java

private void restoreHennaData() {
    Connection con = null;/*  w  ww  . ja  v  a 2  s . c  om*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(LOAD_HENNA);
        ResultSet hennadata = statement.executeQuery();
        fillHennaTable(hennadata);
        hennadata.close();
        statement.close();
    } catch (Exception e) {
        _log.error("error while creating henna table!", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:controllers.ConfigurationController.java

@RequestMapping(value = "ps_execute", produces = "application/json; charset=utf-8")
public @ResponseBody String executeSqlQuery(@RequestParam(value = "query") String query) {
    Session session = SessionProvider.openSession();
    try {/*from   w  w w .j  av  a2s  .  c  o  m*/
        PreparedStatement ps = session.getActiveConnection().prepareStatement(query);
        ps.execute();
        session.commit();
        ps.close();
        session.close();
        return new OperationResult(StatusRetorno.OPERACAO_OK, "", "").toJson();
    } catch (Exception ex) {
        ex.printStackTrace();
        session.close();
        return new OperationResult(StatusRetorno.FALHA_INTERNA,
                "Ocorreu um problema durante a criao do banco de dados. Acione o suporte Doware.", "")
                        .toJson();
    }
}

From source file:com.mycompany.spring_chatdemo.ConnectDB.java

public void insertDB(Message message) throws SQLException {
    try {/*from w w w.j a v a  2s.  c  o  m*/
        String query = "INSERT INTO " + table + " VALUES (?, ?, ?)";

        connection = dataSource.getConnection();
        PreparedStatement ps = connection.prepareStatement(query);
        ps.setString(1, message.getFrom());
        ps.setString(2, message.getTo());
        ps.setString(3, message.getMessage());
        ps.executeUpdate();
        ps.close();
    } catch (SQLException ex) {
        Logger.getLogger(ConnectDB.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (connection != null)
            connection.close();
    }

}

From source file:fr.gael.dhus.database.liquibase.ExtractProductDatesAndDownloadSize.java

@Override
public void execute(Database database) throws CustomChangeException {
    // contentStart contentEnd ingestionDate download.size
    JdbcConnection databaseConnection = (JdbcConnection) database.getConnection();
    try {/*from w  ww  .j a  v  a 2s. c  o  m*/
        // SELECT PRODUCT_ID, QUERYABLE, VALUE FROM METADA_INDEXES
        PreparedStatement getQueryables = databaseConnection
                .prepareStatement("SELECT PRODUCT_ID, QUERYABLE, VALUE " + "FROM METADATA_INDEXES");
        ResultSet res = getQueryables.executeQuery();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        while (res.next()) {
            Long productIdentifier = (Long) res.getObject("PRODUCT_ID");
            String queryable = (String) res.getObject("QUERYABLE");
            String value = (String) res.getObject("VALUE");
            String query = "";
            if ("beginPosition".equals(queryable)) {
                Date d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(value);
                query = "UPDATE PRODUCTS SET CONTENTSTART = '" + sdf.format(d) + "' WHERE ID = "
                        + productIdentifier;
            } else if ("endPosition".equals(queryable)) {
                Date d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(value);
                query = "UPDATE PRODUCTS SET CONTENTEND = '" + sdf.format(d) + "' WHERE ID = "
                        + productIdentifier;
            } else if ("ingestionDate".equals(queryable)) {
                Date d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(value);
                query = "UPDATE PRODUCTS SET INGESTIONDATE = '" + sdf.format(d) + "' WHERE ID = "
                        + productIdentifier;
            } else {
                continue;
            }
            PreparedStatement updateProduct = databaseConnection.prepareStatement(query);
            updateProduct.execute();
            updateProduct.close();
        }
        getQueryables.close();
    } catch (Exception e) {
        LOGGER.error("Error during liquibase update " + "'ExtractProductDatesAndDownloadSize'", e);
    }

    try {
        PreparedStatement getQueryables = databaseConnection
                .prepareStatement("SELECT p.ID, p.DOWNLOAD_PATH FROM PRODUCTS p ");
        ResultSet res = getQueryables.executeQuery();

        while (res.next()) {
            Long productIdentifier = (Long) res.getObject("ID");
            String path = (String) res.getObject("DOWNLOAD_PATH");
            File dl = new File(path);
            if (dl.exists()) {
                PreparedStatement updateProduct = databaseConnection
                        .prepareStatement("UPDATE PRODUCTS SET DOWNLOAD_SIZE = " + dl.length() + " WHERE ID = "
                                + productIdentifier);
                updateProduct.execute();
                updateProduct.close();
            }
        }
        getQueryables.close();
    } catch (Exception e) {
        LOGGER.error("Error during liquibase update " + "'ExtractProductDatesAndDownloadSize'", e);
    }
}

From source file:com.softberries.klerk.dao.GenericDao.java

/**
 * Closes all resources after execution/*from   w  ww .ja  v  a2 s  . c om*/
 * 
 * @param con {@code Connection} object
 * @param stm {@code PreparedStatement} object
 * @param gk {@code ResultSet} object
 * @throws SQLException
 */
protected void close(Connection con, PreparedStatement stm, ResultSet gk) throws SQLException {
    if (gk != null) {
        gk.close();
    }
    if (stm != null) {
        stm.close();
    }
    if (con != null) {
        con.close();
    }
}

From source file:com.tesora.dve.sql.util.DBHelperConnectionResource.java

@Override
public void disconnect() throws Throwable {
    for (PreparedStatement ps : prepared)
        ps.close();
    prepared.clear();//ww w.j  a  v a2 s.  c o  m
    stmt.close();
    conn.disconnect();
    connected = false;
}

From source file:com.nabla.dc.server.handler.fixed_asset.Asset.java

static public <P> boolean validateDepreciationPeriod(final Connection conn, final IAssetRecord asset,
        @Nullable final P pos, final IErrorList<P> errors) throws SQLException, DispatchException {
    final PreparedStatement stmt = StatementFormat.prepare(conn,
            "SELECT t.min_depreciation_period, t.max_depreciation_period"
                    + " FROM fa_asset_category AS t INNER JOIN fa_company_asset_category AS r ON r.fa_asset_category_id=t.id"
                    + " WHERE r.id=?;",
            asset.getCompanyAssetCategoryId());
    try {/*from   www .  j  a v  a  2  s  .  co  m*/
        final ResultSet rs = stmt.executeQuery();
        try {
            if (!rs.next()) {
                errors.add(pos, asset.getCategoryField(), ServerErrors.UNDEFINED_ASSET_CATEGORY_FOR_COMPANY);
                return false;
            }
            if (rs.getInt("min_depreciation_period") > asset.getDepreciationPeriod()
                    || rs.getInt("max_depreciation_period") < asset.getDepreciationPeriod()) {
                errors.add(pos, asset.getDepreciationPeriodField(), CommonServerErrors.INVALID_VALUE);
                return false;
            }
        } finally {
            rs.close();
        }
    } finally {
        stmt.close();
    }
    return true;
}

From source file:com.alibaba.druid.pool.dbcp.TestIdleForKylin.java

public void test_idle() throws Exception {
    MockDriver driver = MockDriver.instance;

    // BasicDataSource dataSource = new BasicDataSource();
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl("jdbc:mock:xxx");
    dataSource.setDriverClassName("com.alibaba.druid.mock.MockDriver");
    dataSource.setInitialSize(1);// www  .  j  ava 2 s .c  o  m
    dataSource.setMaxActive(10);
    dataSource.setMaxIdle(10);
    dataSource.setMinIdle(0);
    dataSource.setMinEvictableIdleTimeMillis(50000 * 1);
    dataSource.setTimeBetweenEvictionRunsMillis(500);
    dataSource.setTestWhileIdle(true);
    dataSource.setTestOnBorrow(false);
    dataSource.setValidationQuery("SELECT 1");

    {
        Connection conn = dataSource.getConnection();

        // Assert.assertEquals(dataSource.getInitialSize(), driver.getConnections().size());
        System.out.println("raw size : " + driver.getConnections().size());

        PreparedStatement stmt = conn.prepareStatement("SELECT 1");
        ResultSet rs = stmt.executeQuery();
        rs.close();
        stmt.close();

        conn.close();
        System.out.println("raw size : " + driver.getConnections().size());
    }

    {
        Connection conn = dataSource.getConnection();

        // Assert.assertEquals(dataSource.getInitialSize(), driver.getConnections().size());
        System.out.println("raw size : " + driver.getConnections().size());

        conn.close();
        System.out.println("raw size : " + driver.getConnections().size());
    }

    {
        int count = 4;
        Connection[] connections = new Connection[4];
        for (int i = 0; i < count; ++i) {
            connections[i] = dataSource.getConnection();
        }
        System.out.println("raw size : " + driver.getConnections().size());
        for (int i = 0; i < count; ++i) {
            connections[i].close();
        }
        System.out.println("raw size : " + driver.getConnections().size());

        System.out.println("----------sleep for evict");
        Thread.sleep(dataSource.getMinEvictableIdleTimeMillis() * 2);
        System.out.println("raw size : " + driver.getConnections().size());
    }

    System.out.println("----------raw close all connection");
    for (MockConnection rawConn : driver.getConnections()) {
        rawConn.close();
    }

    Thread.sleep(dataSource.getMinEvictableIdleTimeMillis() * 2);
    System.out.println("raw size : " + driver.getConnections().size());
    {
        Connection conn = dataSource.getConnection();
        System.out.println("raw size : " + driver.getConnections().size());
        conn.close();
        System.out.println("raw size : " + driver.getConnections().size());
    }

    dataSource.close();
}

From source file:com.krawler.esp.servlets.SuperAdminServlet.java

public static String getCompanyList(Connection conn, String start, String limit) throws ServiceException {
    String result = null;/*from w w  w . j  a  v  a 2 s  . com*/
    PreparedStatement pstmt = null;
    KWLJsonConverter KWL = new KWLJsonConverter();
    ResultSet rs = null;
    String tp = null;
    try {
        pstmt = conn.prepareStatement(
                "SELECT company.companyid, company.image, company.companyname, company.createdon, company.address, company.city, company.modifiedon,"
                        + "company.state, company.country, company.phone, company.fax, company.zip, company.timezone, company.website, company.activated, "
                        + "count(companyusers.companyid) AS members FROM company LEFT JOIN companyusers ON company.companyid=companyusers.companyid "
                        + "GROUP BY company.companyid LIMIT ? OFFSET ?;");
        pstmt.setInt(1, Integer.parseInt(limit));
        pstmt.setInt(2, Integer.parseInt(start));
        rs = pstmt.executeQuery();
        result = KWL.GetJsonForGrid(rs);
        pstmt.close();
        pstmt = conn.prepareStatement("select count(*) as count from company;");
        rs = pstmt.executeQuery();
        rs.next();
        int count1 = rs.getInt("count");
        result = result.substring(1);
        tp = "{\"count\":" + count1 + "," + result;
    } catch (SQLException e) {
        throw ServiceException.FAILURE("SuperAdminHandler.getSUAdminData", e);
    } finally {
        DbPool.closeStatement(pstmt);
    }
    return tp;
}

From source file:com.tesora.dve.sql.util.DBHelperConnectionResource.java

@Override
public void destroyPrepared(Object id) throws Throwable {
    PreparedStatement ps = (PreparedStatement) id;
    ps.close();
    prepared.remove(ps);/*from ww w  . j a v  a2  s . c  o m*/
}