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.instancemanager.FriendListManager.java

public synchronized boolean insert(Integer objId1, Integer objId2) {
    boolean modified = false;

    modified |= _friends.containsKey(objId1) && _friends.get(objId1).add(objId2);
    modified |= _friends.containsKey(objId2) && _friends.get(objId2).add(objId1);

    if (!modified)
        return false;

    Connection con = null;/*ww  w . j  ava2s .  co  m*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection();

        PreparedStatement statement = con.prepareStatement(INSERT_QUERY);
        statement.setInt(1, Math.min(objId1, objId2));
        statement.setInt(2, Math.max(objId1, objId2));

        statement.execute();

        statement.close();
    } catch (SQLException e) {
        _log.warn("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }

    return true;
}

From source file:cn.vko.cache.dao.ha.FailoverMonitorJob.java

@Override
public void run() {
    Future<Integer> future = executor.submit(new Callable<Integer>() {
        @Override/*  w  w  w  .  java2s.c o m*/
        public Integer call() throws Exception {
            Integer result = -1;

            for (int i = 0; i < getRecheckTimes(); i++) {
                Connection conn = null;
                try {
                    conn = getCurrentDetectorDataSource().getConnection();
                    PreparedStatement pstmt = conn.prepareStatement(getDetectingSQL());
                    pstmt.execute();
                    pstmt.close();
                    result = 0;
                    break;
                } catch (Exception e) {
                    logger.warn("(" + (i + 1) + ") check with failure. sleep (" + getRecheckInterval()
                            + ") for next round check.");
                    try {
                        TimeUnit.MILLISECONDS.sleep(getRecheckInterval());
                    } catch (InterruptedException e1) {
                        logger.warn("interrupted when waiting for next round rechecking.");
                    }
                    continue;
                } finally {
                    if (conn != null) {
                        try {
                            conn.close();
                        } catch (SQLException e) {
                            logger.warn("failed to close checking connection:\n", e);
                        }
                    }
                }
            }
            return result;
        }
    });

    try {
        Integer result = future.get(getDetectingRequestTimeout(), TimeUnit.MILLISECONDS);
        if (result == -1) {
            doSwap();
        }
    } catch (InterruptedException e) {
        logger.warn("interrupted when getting query result in FailoverMonitorJob.");
    } catch (ExecutionException e) {
        logger.warn("exception occured when checking failover status in FailoverMonitorJob");
    } catch (TimeoutException e) {
        logger.warn("exceed DetectingRequestTimeout threshold. Switch to standby data source.");
        doSwap();
    }
}

From source file:com.sf.ddao.ops.SelectSqlOperation.java

public Object exec(Context context, Object[] args) throws StatementFactoryException, SQLException {
    PreparedStatement preparedStatement = statementFactory.createStatement(context, false);
    ResultSet resultSet = preparedStatement.executeQuery();
    RSMapper RSMapper = rsMapperFactory.getInstance(args, resultSet);
    final Object res = RSMapper.handle(context, resultSet);
    resultSet.close();/*from  ww w.  j a va2  s.c o m*/
    preparedStatement.close();
    return res;
}

From source file:com.redhat.victims.database.VictimsSQL.java

/**
 * Remove records matching a given hash. This will cascade to all
 * references.//from w  w w.j ava 2s . c  om
 *
 * @param hash
 * @throws SQLException
 */
protected void deleteRecord(Connection connection, String hash) throws SQLException {
    int id = selectRecordId(hash);
    if (id > 0) {
        String[] queries = new String[] { Query.DELETE_FILEHASHES, Query.DELETE_METAS, Query.DELETE_CVES,
                Query.DELETE_RECORD_ID };
        for (String query : queries) {
            PreparedStatement ps = setObjects(connection, query, id);
            ps.execute();
            ps.close();
        }
    }
}

From source file:com.spend.spendService.MainPage.java

public int createCrawl(String queryText, String crawlerName) {
    try {//from  ww  w  . j a va  2  s . c  o m
        String SQL = "SELECT max(crawlid) FROM crawlrecord";
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(SQL);
        int id = 0;
        if (rs.next()) {
            try {
                id = rs.getInt(1);

            } catch (Exception ex) {
            }

        }
        rs.close();

        String SQLi = "INSERT INTO crawlrecord (crawlid,crawlerName,queryText) VALUES (?,?,?)";
        PreparedStatement pstmt = con.prepareStatement(SQLi);
        pstmt.setInt(1, id + 1);
        pstmt.setString(2, crawlerName);
        pstmt.setString(3, queryText);
        pstmt.executeUpdate();
        pstmt.close();
        stmt.close();
        return id + 1;
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:de.iritgo.aktario.jdbc.StoreUser.java

/**
 * Perform the command.//ww w.  j a  v a 2 s .  co m
 */
public void perform() {
    if (properties.get("id") == null) {
        Log.logError("persist", "StoreUser", "Missing unique id for the user to store");

        return;
    }

    UserRegistry userRegistry = Server.instance().getUserRegistry();
    long userId = ((Long) properties.get("id")).longValue();
    User user = userRegistry.getUser(userId);

    if (user == null) {
        Log.logError("persist", "StoreUser", "Unable to find user with id " + userId);

        return;
    }

    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    Connection connection = null;
    PreparedStatement stmt = null;

    try {
        connection = dataSource.getConnection();

        stmt = connection.prepareStatement("delete from IritgoUser where id=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        String userSql = "insert into IritgoUser (id, name, password, email) " + " values (?, ?, ?, ?)";

        stmt = connection.prepareStatement(userSql);
        stmt.setLong(1, userId);
        stmt.setString(2, user.getName());
        stmt.setString(3, user.getPassword());
        stmt.setString(4, user.getEmail());
        stmt.execute();
        stmt.close();

        stmt = connection.prepareStatement("delete from IritgoNamedObjects where userId=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        Log.logVerbose("persist", "StoreUser", "INSERT USER " + userId + " |" + userSql + "|");
    } catch (SQLException x) {
        Log.logError("persist", "StoreUser", "Error while storing user with id " + userId + ": " + x);
    } finally {
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:br.com.mysqlmonitor.monitor.Monitor.java

private void adicionarLog(String descricao) {
    try {//  ww w  .  j ava  2 s .  c om
        logs.append(descricao + "<br/>");
        Connection con = conexaoJDBC.iniciarConexaoLocal();
        PreparedStatement pst = con
                .prepareStatement("INSERT INTO log_agente (DESCRICAO, DATA) values (?, now())");
        pst.setString(1, descricao);
        pst.execute();
        pst.close();
        con.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.wso2telco.util.DBConnection.java

/**
 * Close the database connection.//  w w  w . ja  v  a  2  s .c  o m
 *
 * @param connection Connection instance used by the method call
 * @param statement  prepared Statement used by the method call
 */
public void close(Connection connection, PreparedStatement statement) {

    try {
        if (statement != null)
            statement.close();
        if (connection != null)
            connection.close();
    } catch (Exception e) {
        logger.error("Error occurred while Closing the Connection");
    }
}

From source file:com.redhat.victims.database.VictimsSQL.java

/**
 * Helper function to execute all pending patch operations in the given
 * {@link PreparedStatement}s and close it.
 *
 * @param preparedStatements/*from  w w  w. java  2s . co  m*/
 * @throws SQLException
 */
protected void executeBatchAndClose(PreparedStatement... preparedStatements) throws SQLException {
    for (PreparedStatement ps : preparedStatements) {
        ps.executeBatch();
        ps.clearBatch();
        ps.close();
    }
}

From source file:ca.phon.ipadictionary.impl.DatabaseDictionary.java

@Override
public void removeEntry(String ortho, String ipa) throws IPADictionaryExecption {
    Connection conn = IPADatabaseManager.getInstance().getConnection();
    if (conn != null) {
        String qSt = "DELETE FROM transcript WHERE orthography = ?" + "  AND ipa = ? AND langId = ?";
        try {/*from w  w w . j ava  2s  .co  m*/
            PreparedStatement pSt = conn.prepareStatement(qSt);
            pSt.setString(1, ortho);
            pSt.setString(2, ipa);
            pSt.setString(3, getLanguage().toString());

            pSt.execute();
            pSt.close();
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }
}