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:ece356.UserDBAO.java

public static void writeReview(ReviewData review) throws ClassNotFoundException, SQLException, NamingException {
    Connection con = null;//from  ww w . j a  va 2s  . c o  m
    PreparedStatement pstmt = null;
    try {
        con = getConnection();
        pstmt = con.prepareStatement(
                "INSERT INTO review (doc_username, patient_username, date, rating, comment) VALUES (?, ?, NOW(), ?, ?);");
        pstmt.setString(1, review.getDoctorUsername());
        pstmt.setString(2, review.getPatientUsername());
        pstmt.setInt(3, review.getRating());
        pstmt.setString(4, review.getComment());
        pstmt.executeUpdate();
    } finally {
        if (pstmt != null) {
            pstmt.close();
        }
        if (con != null) {
            con.close();
        }
    }
}

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

@Override
public void addEntry(String ortho, String ipa) throws IPADictionaryExecption {
    Connection conn = IPADatabaseManager.getInstance().getConnection();
    if (conn != null) {
        String qSt = "INSERT INTO transcript (langId, orthography, ipa) VALUES( ?, ?, ? )";

        try {//from w w w. j a va  2  s.c om
            checkLangId(conn);
            PreparedStatement pSt = conn.prepareStatement(qSt);
            pSt.setString(1, getLanguage().toString());
            pSt.setString(2, ortho.toLowerCase());
            pSt.setString(3, ipa);

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

From source file:com.dangdang.ddframe.rdb.sharding.example.config.spring.masterslave.repository.OrderRepositoryImpl.java

@Override
public void insert() {
    String orderSql = "INSERT INTO `t_order` (`order_id`, `user_id`, `status`) VALUES (?, ?, ?)";
    String orderItemSql = "INSERT INTO `t_order_item` (`order_item_id`, `order_id`, `user_id`, `status`) VALUES (?, ?, ?, ?)";
    for (int orderId = 1; orderId <= 4; orderId++) {
        for (int userId = 1; userId <= 2; userId++) {
            try (Connection connection = shardingDataSource.getConnection()) {
                PreparedStatement preparedStatement = connection.prepareStatement(orderSql);
                preparedStatement.setInt(1, orderId);
                preparedStatement.setInt(2, userId);
                preparedStatement.setString(3, "insert");
                preparedStatement.execute();
                preparedStatement.close();

                preparedStatement = connection.prepareStatement(orderItemSql);
                int orderItemId = orderId + 4;
                preparedStatement.setInt(1, orderItemId);
                preparedStatement.setInt(2, orderId);
                preparedStatement.setInt(3, userId);
                preparedStatement.setString(4, "insert");
                preparedStatement.execute();
                preparedStatement.close();
                // CHECKSTYLE:OFF
            } catch (final Exception ex) {
                // CHECKSTYLE:ON
                ex.printStackTrace();//from   w  ww .j  ava  2  s  . c  o m
            }
        }
    }
}

From source file:eu.optimis.ip.gui.client.resources.Accounting.java

/**
 * If DB server is not running, runs it.
 * If Database tables are not created, it creates them.
 * Also prepares all the SQL statements.
 */// ww w  .  j a v  a 2s .co m
private void start() {
    serverThread.startServer();
    try {
        Class.forName(dbconfig.getString("driver"));
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex.getMessage(), ex);
    }

    // If SA user has no password (because the DB does not exist), it creates the SA user and a read-only-user
    try {
        Connection saConnection = DriverManager.getConnection(dbconfig.getString("url"),
                dbconfig.getString("sa.username"), "");
        PreparedStatement ps = saConnection
                .prepareStatement("SET PASSWORD '" + dbconfig.getProperty("sa.password") + "';");
        ps.executeUpdate();
        ps.close();
        saConnection.close();
    } catch (SQLInvalidAuthorizationSpecException ex) {
        Logger.getLogger(Accounting.class.getName()).log(Level.INFO,
                "SA user has already a password. Neither new users are creater nor permissions are re-assigned");
    } catch (SQLException ex) {
        ex.printStackTrace();
    }

    try {
        connection = DriverManager.getConnection(dbconfig.getString("url"), dbconfig.getString("sa.username"),
                dbconfig.getString("sa.password"));
        createDB();

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

    // Drops already defined RO (read-only) user, and creates a new with the password specified in scheduler.properties
    try {
        PreparedStatement ps = connection
                .prepareStatement("DROP USER " + dbconfig.getProperty("ro.username") + ";");
        ps.executeUpdate();
        ps.close();
    } catch (SQLInvalidAuthorizationSpecException ex) {
        Logger.getLogger(Accounting.class.getName()).log(Level.INFO,
                "Don't dropping read-only user because does not exist. Creating...");
    } catch (SQLException ex) {
        Logger.getLogger(Accounting.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
}

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

private SkillSpellbookTable() {
    _skillSpellbooks = new FastMap<Integer, Integer>().setShared(true);

    if (!Config.ALT_SP_BOOK_NEEDED)
        return;//w ww . j  ava 2 s. c o  m

    Connection con = null;

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement("SELECT skill_id, item_id FROM skill_spellbooks");
        ResultSet spbooks = statement.executeQuery();

        while (spbooks.next())
            _skillSpellbooks.put(spbooks.getInt("skill_id"), spbooks.getInt("item_id"));

        spbooks.close();
        statement.close();

        _log.info("SkillSpellbookTable: Loaded " + _skillSpellbooks.size() + " Spellbooks.");
    } catch (Exception e) {
        _log.warn("Error while loading spellbook data: ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:mercury.DigitalMediaDAO.java

public final Integer uploadToDigitalMedia(FileItem file) {
    Connection con = null;//from  w ww  .jav  a2 s.  c  o  m
    Integer serial = 0;
    String filename = file.getName();

    if (filename.lastIndexOf('\\') != -1) {
        filename = filename.substring(filename.lastIndexOf('\\') + 1);
    }

    if (filename.lastIndexOf('/') != -1) {
        filename = filename.substring(filename.lastIndexOf('/') + 1);
    }

    try {
        InputStream is = file.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        serial = getNextSerial("digital_media_id_seq");
        if (serial != 0) {
            con = getDataSource().getConnection();
            con.setAutoCommit(false);
            String sql = " INSERT INTO digital_media " + " (id, file, mime_type, file_name) "
                    + " VALUES (?, ?, ?, ?) ";
            PreparedStatement pstm = con.prepareStatement(sql);
            pstm.setInt(1, serial);
            pstm.setBinaryStream(2, bis, (int) file.getSize());
            pstm.setString(3, file.getContentType());
            pstm.setString(4, filename);
            pstm.executeUpdate();
            pstm.close();
            is.close();
            con.commit();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DAOException(e.getMessage());
    } finally {
        closeConnection(con);
    }
    return serial;
}

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

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

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

    if (!modified)
        return false;

    Connection con = null;// ww w.  j  a va 2  s  .co m
    try {
        con = L2DatabaseFactory.getInstance().getConnection();

        PreparedStatement statement = con.prepareStatement(DELETE_QUERY);
        statement.setInt(1, objId1);
        statement.setInt(2, objId2);
        statement.setInt(3, objId2);
        statement.setInt(4, objId1);

        statement.execute();

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

    return true;
}

From source file:com.chaosinmotion.securechat.server.commands.DropMessages.java

public static void processRequest(UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    ArrayList<Message> messages = new ArrayList<Message>();

    JSONArray a = requestParams.getJSONArray("messages");
    int i, len = a.length();
    for (i = 0; i < len; ++i) {
        JSONObject item = a.getJSONObject(i);
        Message msg = new Message();
        msg.message = item.getInt("messageid");
        msg.checksum = item.getString("checksum");
        messages.add(msg);/*from w  ww.  j  a v a 2s . com*/
    }

    /*
     * Iterate through the messages, deleting each. We only delete a
     * message if message belongs to the user and the checksum matches.
     * This assumes it's our message and it was read with someone who
     * can read the message.
     * 
     * (Thus, the weird query)
     */

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

    try {
        int count = 0;
        c = Database.get();
        ps = c.prepareStatement("DELETE FROM Messages " + "WHERE messageid IN "
                + "    (SELECT Messages.messageid " + "     FROM Messages, Devices "
                + "     WHERE Messages.messageid = ? " + "     AND Messages.checksum = ? "
                + "     AND Devices.deviceid = Messages.deviceid " + "     AND Devices.userid = ?)");

        for (Message msg : messages) {
            /*
             * Get the device ID for this device. Verify it belongs to the
             * user specified
             */

            ps.setInt(1, msg.message);
            ps.setString(2, msg.checksum);
            ps.setInt(3, userinfo.getUserID());
            ps.addBatch();
            ++count;
            if (count > 10240) {
                ps.executeBatch();
            }
        }
        if (count > 0) {
            ps.executeBatch();
        }
    } catch (BatchUpdateException batch) {
        throw batch.getNextException();
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:com.l2jfree.gameserver.communitybbs.bb.Post.java

public void deleteme(Topic t) {
    PostBBSManager.getInstance().delPostByTopic(t);
    Connection con = null;//ww w .  j  a  v  a2s. c om
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con
                .prepareStatement("DELETE FROM posts WHERE post_forum_id=? AND post_topic_id=?");
        statement.setInt(1, t.getForumID());
        statement.setInt(2, t.getID());
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.error(e.getMessage(), e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.alibaba.cobar.client.datasources.ha.FailoverMonitorJob.java

public void run() {
    Future<Integer> future = executor.submit(new Callable<Integer>() {

        public Integer call() throws Exception {
            Integer result = -1;/*from   w  w w .  j a v  a2 s .c  o  m*/

            for (int i = 0; i < getRecheckTimes(); i++) {
                Connection conn = null;
                try {
                    conn = getCurrentDetectorDataSource().getConnection();
                    PreparedStatement pstmt = conn.prepareStatement(getDetectingSQL());
                    pstmt.execute();
                    if (pstmt != null) {
                        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();
    }
}