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.uber.stream.kafka.chaperone.collector.reporter.DbAuditReporter.java

private void closeStatement(PreparedStatement stmt) {
    try {/*from w  w  w.  j  a v  a2s  .c om*/
        if (stmt != null) {
            stmt.close();
        }
    } catch (SQLException e) {
        logger.warn("Got exception to close prepared statement", e);
    }
}

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

@Test
public void preparedStatement() 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   ww  w  . j a  va  2  s . c o m
    assertEquals(1, resultSet.getInt(1));
    assertFalse(resultSet.next());
    resultSet.close();

    statement.close();
    connection.close();
}

From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldDBDAO.java

@Override
public void delete(long aExtendedfieldId) throws IOFailure {
    ArgumentNotValid.checkNotNull(aExtendedfieldId, "aExtendedfieldId");

    Connection c = HarvestDBConnection.get();
    PreparedStatement stm = null;
    try {/*from   ww  w.j a va2s. com*/
        c.setAutoCommit(false);

        stm = c.prepareStatement("DELETE FROM extendedfieldvalue WHERE extendedfield_id = ?");
        stm.setLong(1, aExtendedfieldId);
        stm.executeUpdate();
        stm.close();
        stm = c.prepareStatement("DELETE FROM extendedfield WHERE extendedfield_id = ?");
        stm.setLong(1, aExtendedfieldId);
        stm.executeUpdate();

        c.commit();

    } catch (SQLException e) {
        String message = "SQL error deleting extended fields for ID " + aExtendedfieldId + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(stm);
        DBUtils.rollbackIfNeeded(c, "delete extended field", aExtendedfieldId);
        HarvestDBConnection.release(c);
    }

}

From source file:com.l2jfree.gameserver.model.entity.Hero.java

public void updateHeroes(boolean setDefault) {
    Connection con = null;/* www.ja  v  a2  s  .  co  m*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        if (setDefault) {
            try {
                PreparedStatement statement = con.prepareStatement(UPDATE_ALL);
                statement.execute();
                statement.close();
            } catch (SQLException e) {
                _log.warn("HeroSystem: Couldnt update all Heroes", e);
            }
        } else {
            PreparedStatement statement;

            for (Integer heroId : _heroes.keySet()) {
                StatsSet hero = _heroes.get(heroId);

                if (_completeHeroes == null || !_completeHeroes.containsKey(heroId)) {
                    try {
                        statement = con.prepareStatement(INSERT_HERO);
                        statement.setInt(1, heroId);
                        statement.setInt(2, hero.getInteger(Olympiad.CLASS_ID));
                        statement.setInt(3, hero.getInteger(COUNT));
                        statement.setInt(4, hero.getInteger(PLAYED));
                        statement.execute();
                        statement.close();

                        PreparedStatement statement2 = con.prepareStatement(GET_CLAN_ALLY);
                        statement2.setInt(1, heroId);
                        ResultSet rset2 = statement2.executeQuery();

                        initRelationBetweenHeroAndClan(rset2, hero);

                        rset2.close();
                        statement2.close();

                        _heroes.remove(heroId);
                        _heroes.put(heroId, hero);

                        _completeHeroes.put(heroId, hero);
                    } catch (SQLException e) {
                        _log.warn("HeroSystem: Couldnt insert Heroes", e);
                    }
                } else {
                    try {
                        statement = con.prepareStatement(UPDATE_HERO);
                        statement.setInt(1, hero.getInteger(COUNT));
                        statement.setInt(2, hero.getInteger(PLAYED));
                        statement.setInt(3, heroId);
                        statement.execute();
                        statement.close();
                    } catch (SQLException e) {
                        _log.warn("HeroSystem: Couldnt update Heroes", e);
                    }
                }
            }
        }
    } catch (Exception e) {
        _log.error("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:hermes.store.schema.DefaultJDBCAdapter.java

@Override
public void update(Connection connection, String id, Message message) throws SQLException, JMSException {
    final String messageAsXMLString = xmlHelper.toXML(message);
    final InputStream messageAsXML = new StringInputStream(messageAsXMLString);

    final PreparedStatement pstmt = connection
            .prepareStatement("update messages set message = ? where messageid = ?");
    pstmt.setString(1, message.getJMSMessageID());
    pstmt.setAsciiStream(2, messageAsXML, messageAsXMLString.length());
    pstmt.execute();/*from w ww . ja  va 2 s.  c  o m*/
    pstmt.close();
}

From source file:Controllers.ReportController.java

public int fetchDepartmentId(int accountId) {

    int departmentId = 0;

    try {//from   ww w  .  j  a  v  a2 s  .  com
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource");
        connection = ds.getConnection();

        PreparedStatement pstmt = connection
                .prepareStatement("SELECT * FROM doctors" + " WHERE accountId = ?;");
        pstmt.setInt(1, accountId);
        ResultSet resultSet = pstmt.executeQuery();

        List<Doctor> appointmentsList = new ArrayList<Doctor>();
        while (resultSet.next()) {
            departmentId = resultSet.getInt("departmentId");
        }
        pstmt.close();

    } catch (NamingException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return departmentId;
}

From source file:com.consol.citrus.samples.todolist.dao.JdbcTodoListDao.java

@Override
public void save(TodoEntry entry) {
    try {/*from  w  w  w .j a v a2s . c  o m*/
        Connection connection = getConnection();
        try {
            connection.setAutoCommit(true);
            PreparedStatement statement = connection
                    .prepareStatement("INSERT INTO todo_entries (id, title, description) VALUES (?, ?, ?)");
            try {
                statement.setString(1, getNextId());
                statement.setString(2, entry.getTitle());
                statement.setString(3, entry.getDescription());
                statement.executeUpdate();
            } finally {
                statement.close();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        throw new DataAccessException("Could not save entry " + entry, e);
    }
}

From source file:data.AbstractRepository.java

public void delete(int id) throws DataException {
    try {/* w  w  w .j a  v a  2 s. co m*/
        String query = new StringBuilder("DELETE FROM ").append(DB_TABLE).append(" WHERE id = ").append(id)
                .append(";").toString();

        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
            statement = connection.prepareStatement(query);
            statement.executeUpdate();
        } finally {
            statement.close();
            connection.close();
        }
    } catch (SQLException | NullPointerException e) {
        throw new DataException("Error deleting object from " + DB_TABLE + " with id " + id);
    }
}

From source file:ece356.UserDBAO.java

public static ArrayList<String> querySpecializationTypes() throws ClassNotFoundException, SQLException {
    Connection con = null;/*w  w w.  j a  va  2 s.  c om*/
    PreparedStatement pstmt = null;
    try {
        con = getConnection();

        // Query for general doctor information
        String query = "select specTypeName from specializationType";
        pstmt = con.prepareStatement(query);

        ResultSet resultSet;
        resultSet = pstmt.executeQuery();

        ArrayList<String> specTypeList = new ArrayList<String>();
        while (resultSet.next()) {
            String user = resultSet.getString("specTypeName");
            specTypeList.add(user);
        }
        return specTypeList;
    } catch (Exception e) {
        System.out.println("EXCEPTION:%% " + e);
    } finally {
        if (pstmt != null) {
            pstmt.close();
        }
        if (con != null) {
            con.close();
        }
    }
    return null;
}

From source file:com.cloudera.sqoop.TestMerge.java

public void testMerge() throws Exception {
    createTable();//from  www  . j ava 2  s . c  o m

    // Create a jar to use for the merging process; we'll load it
    // into the current thread CL for when this runs. This needs
    // to contain a different class name than used for the imports
    // due to classloaderstack issues in the same JVM.
    final String MERGE_CLASS_NAME = "ClassForMerging";
    SqoopOptions options = getSqoopOptions(newConf());
    options.setTableName(TABLE_NAME);
    options.setClassName(MERGE_CLASS_NAME);

    CodeGenTool codeGen = new CodeGenTool();
    Sqoop codeGenerator = new Sqoop(codeGen, options.getConf(), options);
    int ret = Sqoop.runSqoop(codeGenerator, new String[0]);
    if (0 != ret) {
        fail("Nonzero exit from codegen: " + ret);
    }

    List<String> jars = codeGen.getGeneratedJarFiles();
    String jarFileName = jars.get(0);

    // Now do the imports.

    Path warehouse = new Path(BaseSqoopTestCase.LOCAL_WAREHOUSE_DIR);

    options = getSqoopOptions(newConf());
    options.setTableName(TABLE_NAME);
    options.setNumMappers(1);

    // Do an import of this data into the "old" dataset.
    options.setTargetDir(new Path(warehouse, "merge-old").toString());
    options.setIncrementalMode(IncrementalMode.DateLastModified);
    options.setIncrementalTestColumn("lastmod");

    ImportTool importTool = new ImportTool();
    Sqoop importer = new Sqoop(importTool, options.getConf(), options);
    ret = Sqoop.runSqoop(importer, new String[0]);
    if (0 != ret) {
        fail("Initial import failed with exit code " + ret);
    }

    // Check that we got records that meet our expected values.
    assertRecordStartsWith("0,0,", "merge-old");
    assertRecordStartsWith("1,42,", "merge-old");

    long prevImportEnd = System.currentTimeMillis();

    Thread.sleep(25);

    // Modify the data in the warehouse.
    PreparedStatement s = conn
            .prepareStatement("UPDATE " + TABLE_NAME + " SET val=43, lastmod=NOW() WHERE id=1");
    try {
        s.executeUpdate();
        conn.commit();
    } finally {
        s.close();
    }

    s = conn.prepareStatement("INSERT INTO " + TABLE_NAME + " VALUES (" + "3,313,NOW())");
    try {
        s.executeUpdate();
        conn.commit();
    } finally {
        s.close();
    }

    Thread.sleep(25);

    // Do another import, into the "new" dir.
    options = getSqoopOptions(newConf());
    options.setTableName(TABLE_NAME);
    options.setNumMappers(1);
    options.setTargetDir(new Path(warehouse, "merge-new").toString());
    options.setIncrementalMode(IncrementalMode.DateLastModified);
    options.setIncrementalTestColumn("lastmod");
    options.setIncrementalLastValue(new Timestamp(prevImportEnd).toString());

    importTool = new ImportTool();
    importer = new Sqoop(importTool, options.getConf(), options);
    ret = Sqoop.runSqoop(importer, new String[0]);
    if (0 != ret) {
        fail("Second import failed with exit code " + ret);
    }

    assertRecordStartsWith("1,43,", "merge-new");
    assertRecordStartsWith("3,313,", "merge-new");

    // Now merge the results!
    ClassLoaderStack.addJarFile(jarFileName, MERGE_CLASS_NAME);

    options = getSqoopOptions(newConf());
    options.setMergeOldPath(new Path(warehouse, "merge-old").toString());
    options.setMergeNewPath(new Path(warehouse, "merge-new").toString());
    options.setMergeKeyCol("ID");
    options.setTargetDir(new Path(warehouse, "merge-final").toString());
    options.setClassName(MERGE_CLASS_NAME);

    MergeTool mergeTool = new MergeTool();
    Sqoop merger = new Sqoop(mergeTool, options.getConf(), options);
    ret = Sqoop.runSqoop(merger, new String[0]);
    if (0 != ret) {
        fail("Merge failed with exit code " + ret);
    }

    assertRecordStartsWith("0,0,", "merge-final");
    assertRecordStartsWith("1,43,", "merge-final");
    assertRecordStartsWith("3,313,", "merge-final");
}