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:jobimtext.thesaurus.distributional.DatabaseThesaurusDatastructure.java

public Long getValuesCount(String key) {
    Long count = 0L;/*from w ww  .j  a v  a  2s .  co m*/
    String sql = "SELECT count FROM " + tableValues + " WHERE feature = ?";
    PreparedStatement ps;
    try {
        ps = getDatabaseConnection().getConnection().prepareStatement(sql);
        ps.setString(1, key);
        ResultSet set = ps.executeQuery();
        if (set.next()) {
            count = set.getLong("count");
        }
        ps.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return count;
}

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

private void deleteTableData() throws SQLException {
    Connection conn = getConnection();
    PreparedStatement statement = conn.prepareStatement("DELETE FROM " + getTableName(),
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    try {/*w w w.j a va2 s .c om*/
        statement.executeUpdate();
        conn.commit();
    } finally {
        statement.close();
    }
}

From source file:jobimtext.thesaurus.distributional.DatabaseThesaurusDatastructure.java

public Long getKeyCount(String key) {
    Long count = 0L;/*w w w .ja  va  2 s .  co  m*/
    String sql = "SELECT count FROM " + tableKey + " WHERE word = ?";
    PreparedStatement ps;
    try {
        ps = getDatabaseConnection().getConnection().prepareStatement(sql);

        ps.setString(1, key);
        ResultSet set = ps.executeQuery();

        if (set.next()) {
            count = set.getLong("count");
        }
        ps.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return count;
}

From source file:com.l2jfree.gameserver.instancemanager.CastleManager.java

public void removeCirclet(L2ClanMember member, int castleId) {
    if (member == null)
        return;// w ww . j  a v a2 s . c  om
    L2Player player = member.getPlayerInstance();
    int circletId = getCircletByCastleId(castleId);

    if (circletId != 0) {
        // Online Player circlet removal
        if (player != null && player.getInventory() != null) {
            L2ItemInstance circlet = player.getInventory().getItemByItemId(circletId);
            if (circlet != null) {
                if (circlet.isEquipped())
                    player.getInventory().unEquipItemInSlotAndRecord(circlet.getLocationSlot());
                player.destroyItemByItemId("CastleCircletRemoval", circletId, 1, player, true);
            }
            return;
        }
        // Else Offline Player circlet removal
        Connection con = null;
        try {
            con = L2DatabaseFactory.getInstance().getConnection();
            PreparedStatement statement = con
                    .prepareStatement("DELETE FROM items WHERE owner_id = ? and item_id = ?");
            statement.setInt(1, member.getObjectId());
            statement.setInt(2, circletId);
            statement.execute();
            statement.close();
        } catch (SQLException e) {
            _log.error("Failed to remove castle circlets offline for player " + member.getName(), e);
        } finally {
            L2DatabaseFactory.close(con);
        }
    }
}

From source file:com.wso2.raspberrypi.Util.java

public static void reservePi(String owner, String macAddress) {
    System.out.println("Changing owner of RPi " + macAddress + " to " + owner);
    BasicDataSource ds = getBasicDataSource();
    Connection dbConnection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;//  ww w.  j  av a 2 s . c  o m
    try {
        dbConnection = ds.getConnection();
        prepStmt = dbConnection.prepareStatement("SELECT * FROM RASP_PI where mac='" + macAddress + "'");
        rs = prepStmt.executeQuery();
        boolean alreadyOwned = false;
        while (rs.next()) {
            String oldOwner = rs.getString("owner");
            if (oldOwner != null && !oldOwner.isEmpty()) {
                alreadyOwned = true;
            }
        }
        if (!alreadyOwned) {
            prepStmt = dbConnection.prepareStatement(
                    "UPDATE RASP_PI SET owner='" + owner + "' where mac='" + macAddress + "'");
            prepStmt.execute();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (dbConnection != null) {
                dbConnection.close();
            }
            if (prepStmt != null) {
                prepStmt.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get a user's data./*from   ww  w .ja  v a  2s  .co m*/
 * 
 * @param userName The username of the desired user.    
 * @return a User object with username, password and type for the requested user.
 * 
 */
public static User getUserData(String userName) {
    User requestedUser = null; // initialize return object

    Connection conn = Conn.initialize(); // Establish connection
    if (conn != null) {
        try {
            if (!MetaDbHelper.userExists(userName)) // If user doesn't exist
                return new User("", "", "", "", 0, ""); //Return a dummy user
            PreparedStatement getUserQuery = conn.prepareStatement(GET_USER_DATA);

            getUserQuery.setString(1, userName); // set parameter
            ResultSet userData = getUserQuery.executeQuery();

            if (userData != null) // The query result was not null
            {
                userData.next();
                // Get parameters
                String password = userData.getString(Global.USER_PASSWORD);
                String type = userData.getString(Global.USER_TYPE);
                String authType = userData.getString(Global.USER_AUTH_TYPE);
                long last_login = userData.getLong(Global.USER_LAST_LOGIN);
                String lastProj = userData.getString(Global.USER_LAST_ACCESS);
                requestedUser = new User(userName, password, type, authType, last_login, lastProj);

            }

            getUserQuery.close();
            userData.close();

            conn.close();
        } catch (Exception e) {
            MetaDbHelper.logEvent(e);
        }
    }
    return requestedUser;
}

From source file:com.l2jfree.gameserver.instancemanager.BlockListManager.java

private BlockListManager() {
    Connection con = null;/* w ww  . j  av a 2s.  com*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection();

        PreparedStatement statement = con.prepareStatement(SELECT_QUERY);
        ResultSet rset = statement.executeQuery();

        while (rset.next()) {
            Integer objectId = L2Integer.valueOf(rset.getInt("charId"));
            String name = rset.getString("name");

            getBlockList(objectId).add(name);
        }

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

    int size = 0;

    for (Set<String> set : _blocks.values())
        size += set.size();

    _log.info("BlockListManager: Loaded " + size + " character block(s).");
}

From source file:com.glaf.activiti.executionlistener.ExtensionSqlExecutionListener.java

public void notify(DelegateExecution execution) throws Exception {
    logger.debug("-------------------------------------------------------");
    logger.debug("--------------ExtensionSQLExecutionListener------------");
    logger.debug("-------------------------------------------------------");

    ActivitiExtensionService service = ExtensionFactory.getActivitiExtensionService();
    CommandContext commandContext = Context.getCommandContext();
    service.setSqlSession(commandContext.getDbSqlSession().getSqlSession());
    ExecutionEntity executionEntity = commandContext.getExecutionEntityManager()
            .findExecutionById(execution.getId());
    String processDefinitionId = executionEntity.getProcessDefinitionId();
    ProcessDefinitionEntity processDefinitionEntity = commandContext.getProcessDefinitionEntityManager()
            .findProcessDefinitionById(processDefinitionId);
    String processName = processDefinitionEntity.getKey();
    ExtensionEntity extension = null;/*from   w w  w . j ava2s  .com*/
    String extendId = null;
    String extensionName = null;

    if (extensionId != null) {
        extensionName = (String) extensionId.getValue(execution);
    }

    if (StringUtils.isNotEmpty(extensionName)) {
        if (extension == null) {
            extendId = processName + "_" + extensionName;
            logger.debug("1--search EX1......");
            extension = service.getExtension(extendId);
        }
        if (extension == null) {
            /**
             * ?????
             */
            logger.debug("2--search EX2......");
            extension = service.getExtensionListener(processName, extensionName);
        }
    }

    if (extension == null) {
        if (StringUtils.isNotEmpty(extensionName)) {
            extension = service.getExtension(extensionName);
        }
    }

    if (extension == null) {
        extension = (ExtensionEntity) execution.getVariableLocal("extension");
    }

    if (LogUtils.isDebug()) {
        logger.debug("extension:" + extension.toJsonObject());
    }

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

    Map<String, Object> variables = execution.getVariables();
    if (variables != null && variables.size() > 0) {
        Iterator<String> iterator = variables.keySet().iterator();
        while (iterator.hasNext()) {
            String variableName = iterator.next();
            if (params.get(variableName) == null) {
                Object value = execution.getVariable(variableName);
                params.put(variableName, value);
            }
        }
    }

    params.put("processInstanceId", execution.getProcessInstanceId());
    params.put("processName", processName);

    StringBuffer buffer = new StringBuffer();
    List<Object> values = null;

    if (extension != null) {
        String sql = extension.getFieldValue("sql");
        if (StringUtils.isNotEmpty(sql)) {
            buffer.append(sql);
            values = ExtensionUtils.getValues(params, extension);
        } else {

            int executionType = 0;
            if (extension.getIntFieldValue("executionType") != 0) {
                executionType = extension.getIntFieldValue("executionType");
            }

            ExtensionEntity ex = null;

            switch (executionType) {
            case -1:
            case -5555:
                ex = service.getExtensionListener("extension_5555");
                break;
            case 30:
            case 1000:
                ex = service.getExtensionListener("extension_1000");
                break;
            case 40:
            case 1002:
                ex = service.getExtensionListener("extension_1002");
                break;
            case 50:
            case 9999:
                ex = service.getExtensionListener("extension_9999");
                break;
            default:
                break;
            }

            if (ex != null) {
                String sql2 = ex.getFieldValue("sql");
                if (StringUtils.isNotEmpty(sql2)) {
                    buffer.append(sql2);
                    values = ExtensionUtils.getValues(params, ex);
                }
            }
        }
    }

    if (buffer.length() == 0) {
        if (execution.getVariable("app_name") != null) {
            extension = service.getExtensionListener("extension_1002");
            if (extension != null) {
                String sql2 = extension.getFieldValue("sql");
                if (StringUtils.isNotEmpty(sql2)) {
                    buffer.append(sql2);
                    values = ExtensionUtils.getValues(params, extension);
                }
            }
        }
    }

    if (buffer.length() > 0) {
        String sql = buffer.toString();

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

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

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

        Connection con = null;
        try {
            con = commandContext.getDbSqlSession().getSqlSession().getConnection();
            PreparedStatement psmt = con.prepareStatement(sql);
            JdbcUtils.fillStatement(psmt, values);
            psmt.executeUpdate();
            psmt.close();
            psmt = null;
        } catch (SQLException ex) {
            throw ex;
        }
    }
}

From source file:com.sap.dirigible.runtime.scripting.DbUtils.java

private void checkSequenceTable(Connection connection) throws SQLException {
    String sql = SELECT_COUNT_FROM + DGB_SEQUENCES;
    PreparedStatement preparedStatement = null;
    try {/*from   w w w  . ja v a2s  .com*/
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.executeQuery();
    } catch (Exception e) {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        sql = CREATE_TABLE + DGB_SEQUENCES + SEQ_NAME_VARCHAR_128_SEQ_VALUE_INTEGER;
        preparedStatement = connection.prepareStatement(sql);
        try {
            preparedStatement.executeUpdate();
        } finally {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        }
    } finally {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
    }

}

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

public void marry() {
    Connection con = null;// w  ww  . j  a v  a 2s .  c o  m
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement;

        statement = con.prepareStatement("UPDATE couples set maried = ?, weddingDate = ? where id = ?");
        statement.setBoolean(1, true);
        _weddingDate = System.currentTimeMillis();
        statement.setLong(2, _weddingDate);
        statement.setInt(3, _id);
        statement.execute();
        statement.close();
        _maried = true;
    } catch (Exception e) {
        _log.error("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}