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.chaosinmotion.securechat.server.commands.AddDevice.java

/**
 * Add device request. Takes parameters for deviceid, pubkey, as well as
 * the user info.//from   w w w  .ja va 2 s.  com
 * @param userinfo
 * @param requestParams
 * @return
 * @throws IOException 
 * @throws SQLException 
 * @throws ClassNotFoundException 
 */
public static boolean processRequest(Login.UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    String deviceid = requestParams.optString("deviceid");
    String pubkey = requestParams.optString("pubkey");

    /*
     * Attempt to insert a new user into the database
     */

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        c = Database.get();

        /*
            * We now have the user index. Insert the device. Note that it is
            * highly unlikely we will have a UUID collision, but we verify
            * we don't by deleting any rows in the device table with the
            * specified UUID. The worse case scenario is a collision which
            * knocks someone else off the air. (The alternative would be
            * to accidentally send the wrong person duplicate messages.)
            * 
            * Note that we don't actually use a device-identifying identifer,
            * choosing instead to pick a UUID, so we need to deal with
            * the possibility (however remote) of duplicate UUIDs.
            * 
            * In the off chance we did have a collision, we also delete all
            * old messages to the device; that prevents messages from being
            * accidentally delivered.
            */

        ps = c.prepareStatement("DELETE FROM Messages " + "WHERE messageid IN "
                + "    (SELECT Messages.messageid " + "     FROM Messages, Devices "
                + "     WHERE Messages.deviceid = Devices.deviceid " + "     AND Devices.deviceuuid = ?)");
        ps.setString(1, deviceid);
        ps.execute();
        ps.close();
        ps = null;

        ps = c.prepareStatement("DELETE FROM Devices WHERE deviceuuid = ?");
        ps.setString(1, deviceid);
        ps.execute();
        ps.close();
        ps = null;

        ps = c.prepareStatement("INSERT INTO Devices " + "    ( userid, deviceuuid, publickey ) " + "VALUES "
                + "    ( ?, ?, ?)");
        ps.setInt(1, userinfo.getUserID());
        ps.setString(2, deviceid);
        ps.setString(3, pubkey);
        ps.execute();

        /*
         * Complete; return result
         */

        return true;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:com.l2jfree.gameserver.idfactory.IdFactory.java

private void cleanUpTimeStamps() {
    Connection con = null;/*  ww w. j ava2s. c  o m*/
    try {
        int cleanCount = 0;
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement stmt;
        for (String line : TIMESTAMPS_CLEAN) {
            stmt = con.prepareStatement(line);
            stmt.setLong(1, System.currentTimeMillis());
            cleanCount += stmt.executeUpdate();
            stmt.close();
        }

        _log.info("Cleaned " + cleanCount + " expired timestamps from database.");
    } catch (SQLException e) {
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.l2jfree.gameserver.model.entity.faction.FactionMember.java

public FactionMember(int playerId, int factionId) {
    _playerId = playerId;//from w  w w .  j  av a 2s .c  om
    _factionId = factionId;
    _factionPoints = 0;
    _contributions = 0;
    _joinDate = System.currentTimeMillis();
    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement;
        statement = con.prepareStatement(
                "INSERT INTO faction_members (player_id, faction_id, faction_points, contributions, join_date) VALUES (?, ?, 0, 0, ?)");
        statement.setInt(1, _playerId);
        statement.setInt(2, _factionId);
        statement.setLong(3, _joinDate);
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:eu.celarcloud.celar_ms.ServerPack.Database.MySQL.DBHandlerWithConnPool.java

private void release(PreparedStatement stmt, Connection conn) {
    try {/*from  w w w .jav  a 2 s  .  c  o  m*/
        if (stmt != null)
            stmt.close();
        if (conn != null)
            conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.viettel.logistic.wms.dao.StockTransDetailDAO.java

public ResultDTO insertStockTransDetail(StockTransDetailDTO stockTransDetailDTO, Connection con) {

    ResultDTO result = new ResultDTO();
    String message = ParamUtils.SUCCESS;
    String key = stockTransDetailDTO.getStockTransId() + "";
    StringBuilder sql = new StringBuilder();
    List params = new ArrayList();

    sql.append("INSERT INTO stock_trans_detail ");
    sql.append(//from  www.  j  ava  2 s .c om
            "(stock_trans_detail_id,stock_trans_id,stock_trans_date,goods_id,goods_code,goods_name,goods_state,goods_unit_type, goods_unit_type_name,goods_is_serial, ");
    sql.append(
            " goods_is_serial_strip,amount_order, amount_real, bincode, barcode,notes, create_datetime,add_infor, ");
    sql.append(" cell_code) ");
    sql.append(
            " VALUES (?,?,to_date(?,'dd/MM/yyyy hh24:mi:ss'),?,?,?,?,?,?,?,?,?,?,?,?,?,to_date(?,'dd/MM/yyyy hh24:mi:ss'),?,?) ");

    //
    params.add(stockTransDetailDTO.getStockTransDetailId());
    params.add(stockTransDetailDTO.getStockTransId());
    params.add(stockTransDetailDTO.getStockTransDate());
    params.add(stockTransDetailDTO.getGoodsId());
    params.add(stockTransDetailDTO.getGoodsCode());
    params.add(stockTransDetailDTO.getGoodsName());
    params.add(stockTransDetailDTO.getGoodsState());
    params.add(stockTransDetailDTO.getGoodsUnitType());
    params.add(stockTransDetailDTO.getGoodsUnitTypeName());
    params.add(stockTransDetailDTO.getGoodsIsSerial());
    params.add(stockTransDetailDTO.getGoodsIsSerialStrip());
    params.add(stockTransDetailDTO.getAmountOrder());
    params.add(stockTransDetailDTO.getAmountReal());
    String bincode = stockTransDetailDTO.getBincode();
    if (!StringUtils.isStringNullOrEmpty(bincode)) {
        params.add(bincode);
    } else {
        params.add("");
    }
    String barcode = stockTransDetailDTO.getBarcode();
    if (!StringUtils.isStringNullOrEmpty(barcode)) {
        params.add(barcode);
    } else {
        params.add("");
    }
    String note = stockTransDetailDTO.getNotes();
    if (!StringUtils.isStringNullOrEmpty(note)) {
        params.add(note);
    } else {
        params.add("");
    }
    params.add(stockTransDetailDTO.getCreateDatetime());
    String addInfo = stockTransDetailDTO.getAddInfor();
    if (!StringUtils.isStringNullOrEmpty(addInfo)) {
        params.add(addInfo);
    } else {
        params.add("");
    }
    String cellCode = stockTransDetailDTO.getCellCode();
    if (!StringUtils.isStringNullOrEmpty(cellCode)) {
        params.add(cellCode);
    } else {
        params.add("");
    }
    //
    try {
        PreparedStatement stm = con.prepareStatement(sql.toString());

        for (int idx = 0; idx < params.size(); idx++) {
            stm.setString(idx + 1, (String) DataUtil.nvl(params.get(idx), ""));
        }
        int num = stm.executeUpdate();
        stm.close();
    } catch (SQLException ex) {
        Logger.getLogger(StockTransDAO.class.getName()).log(Level.SEVERE, null, ex);
        message = ParamUtils.FAIL;
        key = ParamUtils.SYSTEM_OR_DATA_ERROR;
    }

    result.setKey(key);
    result.setMessage(message);
    return result;
    //
}

From source file:com.l2jfree.gameserver.gameobjects.skills.PlayerSkills.java

public void deleteSkill(L2Skill skill) {
    if (skill == null)
        return;//w w  w  .  ja  v a 2s.  c o  m

    final SkillMap map = getSkillMap();

    if (map.remove(skill) == null)
        return;

    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection();

        PreparedStatement statement = con.prepareStatement(
                "DELETE FROM character_skills WHERE skill_id=? AND charId=? AND class_index=?");
        statement.setInt(1, skill.getId());
        statement.setInt(2, getOwner().getObjectId());
        statement.setInt(3, getOwner().getClassIndex());
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

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

/**
 * Saves a castle guard directly to the database.<BR>
 * There are no restrictions for the NPC, however, it will be saved
 * as a NPC guard (not a mercenary)./*from w  w w  .ja v a 2s.  c  om*/
 * @param gm Game Master (player)
 * @param npc any NPC's ID
 */
public final void addAnyGuard(L2Player gm, int npc, int respawn) {
    Castle c = CastleManager.getInstance().getCastle(gm);
    if (c == null) {
        gm.sendMessage("You must be on a castle's ground.");
        return;
    }
    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement ps = con.prepareStatement(ADD_NPC_GUARD);
        ps.setInt(1, c.getCastleId());
        ps.setInt(2, npc);
        ps.setInt(3, gm.getX());
        ps.setInt(4, gm.getY());
        ps.setInt(5, gm.getZ());
        ps.setInt(6, gm.getHeading());
        ps.setInt(7, respawn);
        ps.executeUpdate();
        ps.close();
    } catch (Exception e) {
        _log.warn("Error adding siege guard for castle " + getCastle().getName(), e);
        gm.sendMessage("Failed! Reason: " + e.getMessage());
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.mirth.connect.server.migration.Migrate2_0_0.java

private void updateServerProperty(String name, String value) throws MigrationException {
    PreparedStatement statement = null;
    ResultSet resultSet = null;/*  www. j a  va  2  s. c om*/

    try {
        Connection connection = getConnection();
        statement = connection
                .prepareStatement("UPDATE CONFIGURATION SET VALUE = ? WHERE CATEGORY = 'core' AND NAME = ?");
        statement.setString(1, value);
        statement.setString(2, name);

        if (statement.executeUpdate() == 0) {
            statement.close();
            statement = connection.prepareStatement(
                    "INSERT INTO CONFIGURATION (CATEGORY, NAME, VALUE) VALUES ('core', ?, ?)");
            statement.setString(1, name);
            statement.setString(2, value);
            statement.executeUpdate();
        }
    } catch (SQLException e) {
        throw new MigrationException(e);
    } finally {
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(statement);
    }
}

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

public static void registerRaspberryPi(String macAddress, String ipAddress) {
    System.out.println("Registering Raspberry Pi: " + macAddress + "/" + ipAddress);
    BasicDataSource ds = getBasicDataSource();
    Connection dbConnection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;/*from   ww w . j a  va 2 s.  c  o m*/
    try {
        dbConnection = ds.getConnection();
        prepStmt = dbConnection.prepareStatement("SELECT * FROM RASP_PI WHERE mac='" + macAddress + "'");
        rs = prepStmt.executeQuery();

        if (rs.next()) { // If it exists
            prepStmt = dbConnection.prepareStatement("UPDATE RASP_PI SET ip='" + ipAddress + "',last_updated='"
                    + System.currentTimeMillis() + "' WHERE mac='" + macAddress + "'");
            prepStmt.executeUpdate();
        } else {
            prepStmt = dbConnection.prepareStatement("INSERT INTO RASP_PI (mac,ip,last_updated) VALUES ('"
                    + macAddress + "','" + ipAddress + "','" + System.currentTimeMillis() + "' )");
            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:com.l2jfree.gameserver.instancemanager.InstanceManager.java

public void setInstanceTime(int playerObjId, int id, long time) {
    if (!_playerInstanceTimes.containsKey(playerObjId))
        restoreInstanceTimes(playerObjId);
    Connection con = null;/*from   ww w.j  av  a2s  . com*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement = null;
        statement = con.prepareStatement(ADD_INSTANCE_TIME);
        statement.setInt(1, playerObjId);
        statement.setInt(2, id);
        statement.setLong(3, time);
        statement.setLong(4, time);
        statement.execute();
        statement.close();
        _playerInstanceTimes.get(playerObjId).put(id, time);
    } catch (Exception e) {
        _log.warn("Could not insert character instance time data: ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}