java 代码
- /**
- *
- * Get database connection from the db connection factory. It will set the connection to auto commit as required.
- * Note: autoCommit will be closed only for update statements, but not for query statements.
- *
- * @return A database connection.
- * @throws ChatContactPersistenceException
- * If can't get connection or fails to set the auto commit value.
- */
- private Connection createConnection(boolean autoCommit) throws ChatContactPersistenceException {
- try {
- // create a DB connection
- Connection conn = connectionFactory.createConnection(connectionName);
- // Begin transaction.
- conn.setAutoCommit(autoCommit);
- return conn;
- } catch (DBConnectionException dbce) {
- throw new ChatContactPersistenceException("Can't get the connection from database.", dbce);
- } catch (SQLException sqle) {
- throw new ChatContactPersistenceException("Error while setting auto commit", sqle);
- }
- }
- /**
- *
- * Release the connection. If not success, rollback the transaction.
- *
- * @param conn
- * the connection.
- * @param needRollBack
- * whether rolling back is needed.
- */
- private void releaseConnection(Connection conn, boolean needRollBack) {
- try {
- if (needRollBack && (conn != null) && !conn.isClosed()) {
- conn.rollback();
- }
- } catch (SQLException e) {
- // ignore it
- }
- try {
- if ((conn != null) && !conn.isClosed()) {
- conn.close();
- }
- } catch (SQLException e) {
- // ignore it
- }
- }
- /**
- *
- * Release the statement and result set.
- *
- * @param stmt
- * the statement to release
- * @param result
- * the result to release
- */
- private void releaseStatement(Statement stmt, ResultSet result) {
- try {
- if (result != null) {
- result.close();
- }
- if (stmt != null) {
- stmt.close();
- }
- } catch (SQLException e) {
- // ignore it
- }
- }
- public void addBuddy(long userId, long buddyUserId) throws Exception{
- Connection conn = null;
- boolean success = false;
- PreparedStatement stmt = null;
- try {
- // create a DB connection
- conn = createConnection(false);
- // Insert this buddy if not existed.
- stmt = conn.prepareStatement(SQL_INSERT_BUDDYUSER);
- stmt.setLong(1, userId);
- stmt.setLong(2, buddyUserId);
- stmt.executeUpdate();
- // commit the transaction
- conn.commit();
- success = true;
- } catch (SQLException sqle) {
- throw new ChatContactPersistenceException("Error while processing sql statement", sqle);
- } finally {
- releaseStatement(stmt, null);
- releaseConnection(conn, !success);
- }
- }