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:dao.RuleDao.java

/**
 * Deletes a rule from a target DB and from the local APEX db
 * /*from www . j av a  2s.  c  o  m*/
 * @param id
 * @return
 * @throws Exception
 */
public boolean deleteRule(int id) throws Exception {
    int brgId = 0;
    String name = "";
    PreparedStatement statement = this.getApexConnection()
            .prepareStatement("SELECT BRG_PROJECTID, NAME FROM BUSINESSRULE WHERE ID=?");
    statement.setInt(1, id);
    ResultSet result = statement.executeQuery();
    while (result.next()) {
        brgId = result.getInt("BRG_PROJECTID");
        name = result.getString("NAME");
    }
    statement.close();
    Statement statementTarget = null;

    try {
        Project project = this.getProject(brgId);
        statementTarget = this.getTargetConnection(project.getTargetConfig()).createStatement();
        statementTarget.executeUpdate("DROP TRIGGER " + name.toUpperCase());
        statementTarget.close();
    } catch (Exception e) {
        Logger log = new Logger();
        log.out(Level.ERROR, "deleteRule", "Rule or project doesn't excist");
    }

    Statement statementRemoveApex = this.getApexConnection().createStatement();
    statementRemoveApex.addBatch("DELETE FROM RULE_COLUMN WHERE BUSINESSRULEID=" + id);
    statementRemoveApex.addBatch("DELETE FROM RULE_TABLE WHERE BUSINESSRULEID=" + id);
    statementRemoveApex.addBatch("DELETE FROM RULE_VALUE WHERE BUSINESSRULEID=" + id);
    statementRemoveApex.addBatch("DELETE FROM BUSINESSRULE WHERE ID=" + id);
    statementRemoveApex.executeBatch();
    statementRemoveApex.close();

    return true;
}

From source file:net.lightbody.bmp.proxy.jetty.http.JDBCUserRealm.java

private void loadUser(String username) {
    try {/*from  www. j a  va  2s .  c  o m*/
        if (null == _con)
            connectDatabase();

        if (null == _con)
            throw new SQLException("Can't connect to database");

        PreparedStatement stat = _con.prepareStatement(_userSql);
        stat.setObject(1, username);
        ResultSet rs = stat.executeQuery();

        if (rs.next()) {
            Object key = rs.getObject(_userTableKey);
            put(username, rs.getString(_userTablePasswordField));
            stat.close();

            stat = _con.prepareStatement(_roleSql);
            stat.setObject(1, key);
            rs = stat.executeQuery();

            while (rs.next())
                addUserToRole(username, rs.getString(_roleTableRoleField));

            stat.close();
        }
    } catch (SQLException e) {
        log.warn("UserRealm " + getName() + " could not load user information from database", e);
        connectDatabase();
    }
}

From source file:oobbit.orm.Comments.java

public void add(Comment comment) throws SQLException {
    PreparedStatement statement = getConnection().prepareStatement(
            "INSERT INTO `oobbit`.`comments` (`comment_id`, `link_id`, `creator`, `content`, `create_time`) VALUES (NULL, ?, ?, ?, CURRENT_TIMESTAMP);");
    statement.setInt(1, comment.getLinkId());
    statement.setInt(2, comment.getCreatorId());
    statement.setString(3, comment.getContent());

    statement.executeUpdate();/*from   ww w .  j av a  2  s  .  co m*/
    statement.close();
}

From source file:com.l2jfree.gameserver.communitybbs.Manager.ForumsBBSManager.java

/**
 *
 */// w  ww .  j a v a 2s .c  o m
private void load() {
    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement("SELECT forum_id FROM forums WHERE forum_type=0");
        ResultSet result = statement.executeQuery();
        while (result.next()) {
            int forumId = result.getInt("forum_id");
            Forum f = new Forum(forumId, null);
            addForum(f);
        }
        result.close();
        statement.close();
    } catch (Exception e) {
        _log.warn("data error on Forum (root): ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.l2jfree.gameserver.datatables.TradeListTable.java

protected void dataTimerSave(int time) {
    long timerSave = System.currentTimeMillis() + (long) time * 60 * 60 * 1000;
    Connection con = null;// ww  w.j  a v a2s .  c  o m
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con
                .prepareStatement("UPDATE merchant_buylists SET savetimer =? WHERE time =?");
        statement.setLong(1, timerSave);
        statement.setInt(2, time);
        statement.executeUpdate();
        statement.close();
    } catch (Exception e) {
        _log.fatal("TradeController: Could not update Timer save in Buylist");
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:oobbit.orm.LinkConnections.java

public void update(LinkConnection linkConnection) throws SQLException {
    PreparedStatement statement = getConnection().prepareStatement(
            "UPDATE `oobbit`.`connections` SET `title` = ? WHERE `connections`.`source_link_id` = ? AND `connections`.`destination_link_id` = ?;");
    statement.setString(1, linkConnection.getTitle());
    statement.setInt(2, linkConnection.getSourceLinkId());
    statement.setInt(3, linkConnection.getDestinationLinkId());

    statement.executeUpdate();/*from ww  w.j  a  v a  2s .  c  o m*/
    statement.close();
}

From source file:com.cloudera.sqoop.manager.TestSqlManager.java

@Test
public void getPrimaryKeyFromTable() {
    // first, create a table with a primary key
    Connection conn = null;//from w ww.ja va2s  .co m
    try {
        conn = testServer.getConnection();
        PreparedStatement statement = conn.prepareStatement(
                "CREATE TABLE " + TABLE_WITH_KEY + "(" + KEY_FIELD_NAME + " INT NOT NULL PRIMARY KEY, foo INT)",
                ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        statement.executeUpdate();
        statement.close();
    } catch (SQLException sqlException) {
        fail("Could not create table with primary key: " + sqlException.toString());
    } finally {
        if (null != conn) {
            try {
                conn.close();
            } catch (SQLException sqlE) {
                LOG.warn("Got SQLException during close: " + sqlE.toString());
            }
        }
    }

    String primaryKey = manager.getPrimaryKey(TABLE_WITH_KEY);
    assertEquals("Expected null pkey for table without key", primaryKey, KEY_FIELD_NAME);
}

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

private void deleteItemsInDb() {
    Connection con = null;/*from   w  w w  .j a va 2s.c  o m*/

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(DELETE_ITEMS);
        statement.execute();
        statement.close();
    } catch (SQLException e) {
        _log.error("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.flexive.ejb.beans.LanguageBean.java

/**
 * Check if the given language is referenced from a table
 *
 * @param con      an open and valid connection
 * @param language the language to check
 * @return if the language is in use/* w  ww.  j a  v a  2s .  c  o m*/
 * @throws FxApplicationException on errors
 * @throws SQLException           on errors
 */
private boolean hasUsages(Connection con, FxLanguage language) throws FxApplicationException, SQLException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Checking for uses of language " + language.getIso2digit());
    }
    PreparedStatement ps = null;
    try {
        ResultSet rs;
        for (String[] check : LANG_USAGE) {
            if (ps != null)
                ps.close();
            ps = con.prepareStatement("SELECT COUNT(*) FROM " + check[0] + " WHERE " + check[1] + "=?");
            ps.setLong(1, language.getId());
            rs = ps.executeQuery();
            if (rs != null && rs.next()) {
                if (rs.getLong(1) > 0) {
                    LOG.info("Language [" + language.getIso2digit() + "] has [" + rs.getLong(1)
                            + "] usages in table " + check[0] + ", column " + check[1]);
                    return true;
                }
            }
        }
    } finally {
        if (ps != null)
            ps.close();
    }
    return false;
}

From source file:com.glaf.jbpm.action.SQLAction.java

public void execute(ExecutionContext ctx) throws Exception {
    logger.debug("---------------------------------------------------");
    logger.debug("----------------------SQLAction--------------------");
    logger.debug("---------------------------------------------------");

    ContextInstance contextInstance = ctx.getContextInstance();

    Map<String, Object> params = new java.util.HashMap<String, Object>();

    Map<String, Object> variables = contextInstance.getVariables();
    if (variables != null && variables.size() > 0) {
        Set<Entry<String, Object>> entrySet = variables.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            String name = entry.getKey();
            Object value = entry.getValue();
            if (name != null && value != null && params.get(name) == null) {
                params.put(name, value);
            }/*  w w  w . j a v a 2 s  .  c  o m*/
        }
    }

    ProcessInstance processInstance = ctx.getProcessInstance();
    ProcessDefinition processDefinition = processInstance.getProcessDefinition();

    params.put("processInstanceId", processInstance.getId());
    params.put("processName", processDefinition.getName());
    params.put("processDefinitionId", processDefinition.getId());
    params.put("processDefinition", processDefinition);
    params.put("processInstance", processInstance);

    boolean executable = true;

    if (StringUtils.isNotEmpty(expression)) {
        if (expression.startsWith("#{") && expression.endsWith("}")) {
            Object value = DefaultExpressionEvaluator.evaluate(expression, params);
            if (value != null) {
                if (value instanceof Boolean) {
                    Boolean b = (Boolean) value;
                    executable = b.booleanValue();
                }
            }
        }
    }

    if (!executable) {
        logger.debug("???false??");
        return;
    }

    List<Object> values = new java.util.ArrayList<Object>();

    if (elements != null) {
        values = ExpressionUtils.getValues(ctx, elements);
    }

    sql = QueryUtils.replaceSQLParas(sql, params);

    if (sql.indexOf("#{tableName}") != -1) {
        String tableName = (String) contextInstance.getVariable("tableName");
        if (StringUtils.isNotEmpty(tableName)) {
            sql = StringTools.replace(sql, "#{tableName}", tableName);
        }
    }

    if (sql.indexOf("#{") != -1 && sql.indexOf("}") != -1) {
        sql = (String) DefaultExpressionEvaluator.evaluate(sql, params);
    }

    if (LogUtils.isDebug()) {
        logger.debug(sql);
        logger.debug(values);
    }

    Connection con = null;
    PreparedStatement psmt = null;
    try {
        con = ctx.getJbpmContext().getConnection();
        psmt = con.prepareStatement(sql);
        JdbcUtils.fillStatement(psmt, values);
        psmt.executeUpdate();
        psmt.close();
        psmt = null;
    } finally {
        if (psmt != null) {
            psmt.close();
            psmt = null;
        }
    }
}