Example usage for java.sql PreparedStatement isClosed

List of usage examples for java.sql PreparedStatement isClosed

Introduction

In this page you can find the example usage for java.sql PreparedStatement isClosed.

Prototype

boolean isClosed() throws SQLException;

Source Link

Document

Retrieves whether this Statement object has been closed.

Usage

From source file:com.cloud.utils.db.TransactionLegacy.java

/**
 * Receives a list of {@link PreparedStatement} and quietly closes all of them, which
 * triggers also closing their dependent objects, like a {@link ResultSet}
 *
 * @param pstmt2Close// w  ww.ja  v a2  s.  c  om
 */
public static void closePstmts(List<PreparedStatement> pstmt2Close) {
    for (PreparedStatement pstmt : pstmt2Close) {
        try {
            if (pstmt != null && !pstmt.isClosed()) {
                pstmt.close();
            }
        } catch (SQLException e) {
            // It's not possible to recover from this and we need to continue closing
            e.printStackTrace();
        }
    }
}

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

@Test
public void preparedStatementClose() throws Exception {
    CassandraDataSource connectionPoolDataSource = new CassandraDataSource(HOST, PORT, KEYSPACE, USER, PASSWORD,
            VERSION, CONSISTENCY, TRUST_STORE, TRUST_PASS);

    DataSource pooledCassandraDataSource = new PooledCassandraDataSource(connectionPoolDataSource);

    Connection connection = pooledCassandraDataSource.getConnection();

    PreparedStatement statement = connection
            .prepareStatement("SELECT someInt FROM pooled_test WHERE somekey = ?");
    statement.setString(1, "world");

    ResultSet resultSet = statement.executeQuery();
    assertTrue(resultSet.next());//from w w  w .  j  av  a2  s  .c  o m
    assertEquals(1, resultSet.getInt(1));
    assertFalse(resultSet.next());
    resultSet.close();

    connection.close();

    assert statement.isClosed();
}

From source file:com.yahoo.ycsb.db.PostgreSQLJsonbClient.java

@Override
public void cleanup() throws DBException {
    if (batchSize > 0) {
        try {//w  w  w  .j a  v a 2s .  c  o m
            // commit un-finished batches
            for (PreparedStatement st : cachedStatements.values()) {
                if (!st.getConnection().isClosed() && !st.isClosed() && (numRowsInBatch % batchSize != 0)) {
                    st.executeBatch();
                }
            }
        } catch (SQLException e) {
            System.err.println("Error in cleanup execution. " + e);
            throw new DBException(e);
        }
    }

    try {
        cleanupAllConnections();
    } catch (SQLException e) {
        System.err.println("Error in closing the connection. " + e);
        throw new DBException(e);
    }
}

From source file:com.alibaba.druid.benckmark.pool.Oracle_Case4.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();/*from  w  ww.  java 2 s. c om*/

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();

                        int mod = i % 500;

                        String sql = SQL; // + " AND ROWNUM <= " + (mod + 1);
                        PreparedStatement stmt = conn.prepareStatement(sql);
                        stmt.setInt(1, 61);
                        ResultSet rs = stmt.executeQuery();
                        int rowCount = 0;
                        while (rs.next()) {
                            rowCount++;
                        }
                        // Assert.isTrue(!rs.isClosed());
                        rs.close();
                        // Assert.isTrue(!stmt.isClosed());
                        stmt.close();
                        Assert.isTrue(stmt.isClosed());
                        conn.close();
                        Assert.isTrue(conn.isClosed());
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}

From source file:com.base2.kagura.core.report.connectors.FreemarkerSQLDataReportConnector.java

/**
 * Runs freemarker against the 3 sql queries, then executes them in order.
 * {@inheritDoc}/* w ww . j  av  a  2s  .c o m*/
 */
@Override
public void runReport(Map<String, Object> extra) {
    PreparedStatement prestatement = null;
    PreparedStatement poststatement = null;
    PreparedStatement statement = null;
    try {
        getStartConnection();
        if (StringUtils.isNotBlank(presql)) {
            FreemarkerSQLResult prefreemarkerSQLResult = freemakerParams(extra, false, presql);
            prestatement = connection.prepareStatement(prefreemarkerSQLResult.getSql());
            for (int i = 0; i < prefreemarkerSQLResult.getParams().size(); i++) {
                prestatement.setObject(i + 1, prefreemarkerSQLResult.getParams().get(i));
            }
            prestatement.setQueryTimeout(queryTimeout);
            prestatement.execute();
        }
        FreemarkerSQLResult freemarkerSQLResult = freemakerParams(extra, true, freemarkerSql);
        statement = connection.prepareStatement(freemarkerSQLResult.getSql());
        for (int i = 0; i < freemarkerSQLResult.getParams().size(); i++) {
            statement.setObject(i + 1, freemarkerSQLResult.getParams().get(i));
        }
        statement.setQueryTimeout(queryTimeout);
        rows = resultSetToMap(statement.executeQuery());
        if (StringUtils.isNotBlank(postsql)) {
            FreemarkerSQLResult postfreemarkerSQLResult = freemakerParams(extra, false, postsql);
            poststatement = connection.prepareStatement(postfreemarkerSQLResult.getSql());
            for (int i = 0; i < postfreemarkerSQLResult.getParams().size(); i++) {
                poststatement.setObject(i + 1, postfreemarkerSQLResult.getParams().get(i));
            }
            poststatement.setQueryTimeout(queryTimeout);
            poststatement.execute();
        }
    } catch (Exception ex) {
        errors.add(ex.getMessage());
    } finally {
        try {
            if (statement != null && !statement.isClosed()) {
                statement.close();
                statement = null;
            }
            if (prestatement != null && !prestatement.isClosed()) {
                prestatement.close();
                prestatement = null;
            }
            if (poststatement != null && !poststatement.isClosed()) {
                poststatement.close();
                poststatement = null;
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
            errors.add(e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

private OperationResponse delete(final AbstractEntity record, final Connection conn) throws Exception {
    OperationResponse response = new OperationResponse();
    Class<?> type = record.getClass();

    SimpleDbQuery parser = new SimpleDbQuery();

    String sql = parser.getDeleteQuery(type);

    PreparedStatement pstmnt = conn.prepareStatement(sql);

    try {//  w w  w  . j  av a2s  . c o  m
        List<StructAttributeReflect> keyattrs = new ArrayList<StructAttributeReflect>();

        StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(type);
        response.setEntity(enref.Entity);
        response.setKey(getEntityKey(record));

        for (StructAttributeReflect attr : enref.Attributes) {
            if (attr == null) {
                continue;
            }
            if (attr.IsKeyColumn) {
                keyattrs.add(attr);
            }
        }
        for (int ii = 0; ii < keyattrs.size(); ii++) {
            Object value = PropertyUtils.getSimpleProperty(record, keyattrs.get(ii).Field.getName());
            setPreparedValue(pstmnt, ii + 1, keyattrs.get(ii), value, record);
        }

        int count = pstmnt.executeUpdate();
        if (count > 0) {
            response.setOperation(EnumPersistenceOperation.Deleted);
        } else {
            response.setOperation(EnumPersistenceOperation.Ignored);
        }
        log.debug("[" + record.getClass().getCanonicalName() + "] deleted [count=" + count + "]");
        return response;
    } finally {
        if (pstmnt != null && !pstmnt.isClosed()) {
            pstmnt.close();
        }
    }
}

From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java

/**
 * @see edu.uga.cs.fluxbuster.db.DBInterface#storeClusterClasses(java.util.Date, java.util.Map, boolean)
 *//*from   w  w w  . j a  v  a 2 s  . c o m*/
@Override
public void storeClusterClasses(Date logdate, Map<ClusterClass, List<StoredDomainCluster>> clusterClasses,
        boolean validated) {
    String logDateTable = dateFormatTable.format(logdate);

    Connection con = null;
    PreparedStatement clusterClassesInsertStmt = null;
    try {
        con = this.getConnection();
        clusterClassesInsertStmt = con.prepareStatement(
                "INSERT INTO cluster_classes_" + logDateTable + " VALUES (?, 'SIE', ?, ?, ?)");
        for (ClusterClass clusclass : clusterClasses.keySet()) {
            for (StoredDomainCluster cluster : clusterClasses.get(clusclass)) {
                clusterClassesInsertStmt.setInt(1, cluster.getClusterId());
                clusterClassesInsertStmt.setDate(2, new java.sql.Date(logdate.getTime()));
                clusterClassesInsertStmt.setString(3, clusclass.toString());
                clusterClassesInsertStmt.setBoolean(4, validated);
                this.executePreparedStatementNoResult(con, clusterClassesInsertStmt);
            }
        }
    } catch (SQLException e) {
        if (log.isErrorEnabled()) {
            log.error("Error storing cluster classes.", e);
        }
    } finally {
        try {
            if (clusterClassesInsertStmt != null && !clusterClassesInsertStmt.isClosed()) {
                clusterClassesInsertStmt.close();
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error("e");
            }
        }
        try {
            if (con != null && !con.isClosed()) {
                con.close();
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error("e");
            }
        }
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

private OperationResponse insert(final AbstractEntity record, final Connection conn) throws Exception {
    Class<?> type = record.getClass();
    OperationResponse response = new OperationResponse();

    SimpleDbQuery parser = new SimpleDbQuery();

    String sql = parser.getInsertQuery(type);
    PreparedStatement pstmnt = conn.prepareStatement(sql);
    try {/*from  w  w w  . ja v  a 2s.  c o  m*/
        StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(type);
        response.setEntity(enref.Entity);
        response.setKey(getEntityKey(record));

        int index = 1;
        for (StructAttributeReflect attr : enref.Attributes) {
            if (attr == null) {
                continue;
            }

            Object value = PropertyUtils.getSimpleProperty(record, attr.Field.getName());
            if (value == null) {
                if (attr.IsKeyColumn && attr.AutoIncrement) {
                    Entity entity = record.getClass().getAnnotation(Entity.class);
                    value = getSequenceValue(entity, attr, conn);
                }
            }
            if (attr.Reference != null) {
                boolean overwrite = false;
                if (attr.Reference.CascadeUpdate) {
                    overwrite = true;
                }
                save((AbstractEntity) value, conn, overwrite);
                StructAttributeReflect rattr = ReflectionUtils.get().getAttribute(value.getClass(),
                        attr.Reference.Field);
                value = PropertyUtils.getProperty(value, rattr.Field.getName());
            } else if (attr.Column.compareTo(AbstractPersistedEntity._TX_TIMESTAMP_COLUMN_) == 0) {
                value = new Date();
            }
            setPreparedValue(pstmnt, index, attr, value, record);
            index++;
        }
        int count = pstmnt.executeUpdate();
        if (count > 0) {
            response.setOperation(EnumPersistenceOperation.Inserted);
        } else {
            response.setOperation(EnumPersistenceOperation.Ignored);
        }
        log.debug("[" + record.getClass().getCanonicalName() + "] created [count=" + count + "]");
        return response;
    } finally {
        if (pstmnt != null && !pstmnt.isClosed()) {
            pstmnt.close();
        }
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

private OperationResponse update(final AbstractEntity record, final Connection conn) throws Exception {
    Class<?> type = record.getClass();
    OperationResponse response = new OperationResponse();

    SimpleDbQuery parser = new SimpleDbQuery();

    String sql = parser.getUpdateQuery(type);

    PreparedStatement pstmnt = conn.prepareStatement(sql);

    try {/*from   w ww . j ava 2 s.co  m*/
        List<StructAttributeReflect> keyattrs = new ArrayList<StructAttributeReflect>();

        StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(type);

        response.setEntity(enref.Entity);
        response.setKey(getEntityKey(record));

        int index = 1;
        for (StructAttributeReflect attr : enref.Attributes) {
            if (attr == null) {
                continue;
            }

            if (attr.IsKeyColumn) {
                keyattrs.add(attr);
                continue;
            }

            Object value = PropertyUtils.getSimpleProperty(record, attr.Field.getName());
            if (attr.Reference != null && attr.Reference.CascadeUpdate) {
                save((AbstractEntity) value, conn, true);
                StructAttributeReflect rattr = ReflectionUtils.get().getAttribute(value.getClass(),
                        attr.Reference.Field);
                value = PropertyUtils.getProperty(value, rattr.Field.getName());
            } else if (attr.Column.compareTo(AbstractPersistedEntity._TX_TIMESTAMP_COLUMN_) == 0) {
                value = new Date();
                keyattrs.add(attr);
            }
            setPreparedValue(pstmnt, index, attr, value, record);
            index++;
        }
        for (int ii = 0; ii < keyattrs.size(); ii++) {
            Object value = PropertyUtils.getSimpleProperty(record, keyattrs.get(ii).Field.getName());
            setPreparedValue(pstmnt, (index + ii), keyattrs.get(ii), value, record);
        }

        int count = pstmnt.executeUpdate();
        if (count > 0) {
            response.setOperation(EnumPersistenceOperation.Updated);
        } else {
            response.setOperation(EnumPersistenceOperation.Ignored);
        }
        log.debug("[" + record.getClass().getCanonicalName() + "] updated [count=" + count + "]");
        return response;
    } finally {
        if (pstmnt != null && !pstmnt.isClosed()) {
            pstmnt.close();
        }
    }
}

From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java

/**
 * @see edu.uga.cs.fluxbuster.db.DBInterface#storeClusters(java.util.List, java.lang.String, java.util.Date)
 *///w w  w  .j a  va 2s.  c  o m
@Override
public void storeClusters(List<DomainCluster> clusters, String sensorname, Date logdate) {

    String logDateTable = dateFormatTable.format(logdate);

    Connection con = null;
    PreparedStatement domainsInsertStmt = null;
    PreparedStatement domainsSelectStmt = null;
    PreparedStatement clustersInsertStmt = null;
    PreparedStatement resolvedIPSInsertStmt = null;
    PreparedStatement clusterResolvedIPSInsertStmt = null;
    PreparedStatement clusterFeatureVectorsInsertStmt = null;

    try {
        con = this.getConnection();
        domainsInsertStmt = con
                .prepareStatement("INSERT INTO domains_" + logDateTable + " VALUES(DEFAULT, ?, ?, ?)");
        domainsSelectStmt = con
                .prepareStatement("SELECT domain_id FROM domains_" + logDateTable + " WHERE domain_name = ?");
        clustersInsertStmt = con
                .prepareStatement("INSERT INTO clusters_" + logDateTable + " VALUES " + "(?, ?, ?, ?)");
        resolvedIPSInsertStmt = con
                .prepareStatement("INSERT INTO resolved_ips_" + logDateTable + " VALUES " + "( ?, ?, inet(?))");
        clusterResolvedIPSInsertStmt = con.prepareStatement(
                "INSERT INTO cluster_resolved_ips_" + logDateTable + " VALUES " + "( ?, ?, ?, inet(?))");
        clusterFeatureVectorsInsertStmt = con.prepareStatement("INSERT INTO cluster_feature_vectors_"
                + logDateTable + "(cluster_id, sensor_name, log_date, network_cardinality, ip_diversity, "
                + "number_of_domains, ttl_per_domain, ip_growth_ratio, queries_per_domain, avg_last_growth_ratio_single_entry, "
                + "avg_last_growth_ratio_entries, avg_last_growth_prefix_ratio_entries, last_growth_ratio_cluster,"
                + "last_growth_prefix_ratio_cluster) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        int clusterId = 1;
        for (DomainCluster cluster : clusters) {
            for (CandidateFluxDomain candidateDomain : cluster.getCandidateDomains()) {
                String domainName = filterChars(candidateDomain.getDomainName());
                String domainNameRev = DomainNameUtils.reverseDomainName(domainName);
                String secondLevelDomainName = DomainNameUtils.extractEffective2LD(domainName);
                String secondLevelDomainNameRev = null;
                if (secondLevelDomainName != null) {
                    secondLevelDomainNameRev = DomainNameUtils.reverseDomainName(secondLevelDomainName);
                } else {
                    secondLevelDomainNameRev = DomainNameUtils.reverseDomainName(domainName);
                }

                domainsInsertStmt.setString(1, domainNameRev);
                domainsInsertStmt.setDate(2, new java.sql.Date(logdate.getTime()));
                domainsInsertStmt.setString(3, secondLevelDomainNameRev);
                executePreparedStatementNoResult(con, domainsInsertStmt);

                domainsSelectStmt.setString(1, domainNameRev);
                ResultSet rs = this.executePreparedStatementWithResult(con, domainsSelectStmt);

                try {
                    if (rs.next()) {
                        int domainId = rs.getInt(1);

                        clustersInsertStmt.setInt(1, clusterId);
                        clustersInsertStmt.setInt(2, domainId);
                        clustersInsertStmt.setString(3, sensorname);
                        clustersInsertStmt.setDate(4, new java.sql.Date(logdate.getTime()));

                        this.executePreparedStatementNoResult(con, clustersInsertStmt);

                        for (InetAddress resolvedIP : candidateDomain.getIps()) {
                            resolvedIPSInsertStmt.setInt(1, domainId);
                            resolvedIPSInsertStmt.setDate(2, new java.sql.Date(logdate.getTime()));
                            resolvedIPSInsertStmt.setString(3, resolvedIP.getHostAddress());

                            this.executePreparedStatementNoResult(con, resolvedIPSInsertStmt);

                        }
                    }
                } catch (SQLException ex) {
                    if (log.isErrorEnabled()) {
                        log.error("", ex);
                    }
                } finally {
                    rs.close();
                }
            }

            /*String nickname = getNicknames((List<String>)cluster.getDomains());
            insertQuery = "INSERT INTO cluster_nicknames_"+ logDateTable +" VALUES" +
             "("+clusterId+", '"+sensorname+"', '"+logDateStr+"', '"+nickname+"')";
                    
            performInsertQuery(insertQuery, clusterNicknamesCreateQuery);*/

            for (InetAddress resolvedIP : cluster.getIps()) {
                clusterResolvedIPSInsertStmt.setInt(1, clusterId);
                clusterResolvedIPSInsertStmt.setString(2, sensorname);
                clusterResolvedIPSInsertStmt.setDate(3, new java.sql.Date(logdate.getTime()));
                clusterResolvedIPSInsertStmt.setString(4, resolvedIP.getHostAddress());

                this.executePreparedStatementNoResult(con, clusterResolvedIPSInsertStmt);
            }

            clusterFeatureVectorsInsertStmt.setInt(1, clusterId);
            clusterFeatureVectorsInsertStmt.setString(2, sensorname);
            clusterFeatureVectorsInsertStmt.setDate(3, new java.sql.Date(logdate.getTime()));
            clusterFeatureVectorsInsertStmt.setInt(4, cluster.getIps().size());
            clusterFeatureVectorsInsertStmt.setDouble(5, cluster.getIpDiversity());
            clusterFeatureVectorsInsertStmt.setInt(6, cluster.getDomains().size());
            clusterFeatureVectorsInsertStmt.setDouble(7, cluster.getAvgTTLPerDomain());
            clusterFeatureVectorsInsertStmt.setDouble(8, cluster.getIpGrowthRatio());
            clusterFeatureVectorsInsertStmt.setDouble(9, cluster.getQueriesPerDomain());

            Double temp = cluster.getAvgLastGrowthRatioSingleEntry();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(10, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(10, temp);
            }

            temp = cluster.getAvgLastGrowthRatioEntries();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(11, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(11, temp);
            }

            temp = cluster.getAvgLastGrowthPrefixRatioEntries();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(12, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(12, temp);
            }

            temp = cluster.getLastGrowthRatioCluster();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(13, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(13, temp);
            }

            temp = cluster.getLastGrowthPrefixRatioCluster();
            if (temp == null) {
                clusterFeatureVectorsInsertStmt.setNull(14, java.sql.Types.REAL);
            } else {
                clusterFeatureVectorsInsertStmt.setDouble(14, temp);
            }

            this.executePreparedStatementNoResult(con, clusterFeatureVectorsInsertStmt);

            clusterId++;
        }
    } catch (SQLException e) {
        if (log.isErrorEnabled()) {
            log.error("", e);
        }
    } finally {
        try {
            if (domainsInsertStmt != null && !domainsInsertStmt.isClosed()) {
                domainsInsertStmt.close();
            }
            if (domainsSelectStmt != null && !domainsSelectStmt.isClosed()) {
                domainsSelectStmt.close();
            }
            if (clustersInsertStmt != null && !clustersInsertStmt.isClosed()) {
                clustersInsertStmt.close();
            }
            if (resolvedIPSInsertStmt != null && !resolvedIPSInsertStmt.isClosed()) {
                resolvedIPSInsertStmt.close();
            }
            if (clusterResolvedIPSInsertStmt != null && !clusterResolvedIPSInsertStmt.isClosed()) {
                clusterResolvedIPSInsertStmt.close();
            }
            if (clusterFeatureVectorsInsertStmt != null && !clusterFeatureVectorsInsertStmt.isClosed()) {
                clusterFeatureVectorsInsertStmt.close();
            }
            if (con != null && !con.isClosed()) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}