Example usage for java.sql Connection rollback

List of usage examples for java.sql Connection rollback

Introduction

In this page you can find the example usage for java.sql Connection rollback.

Prototype

void rollback() throws SQLException;

Source Link

Document

Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.

Usage

From source file:dao.PblogTopicDaoDb.java

/**
 * add a new topic in personal blog - allow the users to personalize the information
 * @param topic - new topic to add//from w  w w . j a  v a2 s.c o m
 * @param message - new message (can include HTML/digital content)
 * @param userId - user id or the blogger id
 * @param userLogin - user login of the blogger
 * @param fontSize - font size for the topic
 * @param fontFace - font face for the topic
 * @param fontColor - font color for the topic
 * @param moodId - mood id for this topic
 * @param bgColor - background color for the topic
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
*/
public void addPblogTopic(String topic, String message, String userId, String userLogin, String fontSize,
        String fontFace, String fontColor, String moodId, String bgColor, String usertags)
        throws BaseDaoException {

    /**
     * userid same as pblogid
     */
    if (RegexStrUtil.isNull(message) && RegexStrUtil.isNull(topic)) {
        throw new BaseDaoException("message and topic are null");
    }

    if (RegexStrUtil.isNull(userId) || RegexStrUtil.isNull(userLogin)) {
        throw new BaseDaoException("params are null");
    }

    /**
     *  Get scalability datasource for pblogtopics - partition on userId (pBlogId)
     */
    String sourceName = scalabilityManager.getWriteScalability(userId);
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, addPblogTopic() " + sourceName + " userId = " + userId);
    }

    List tidResult = null;
    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        addQuery.run(conn, userId, message, topic);
        addAttrQuery.run(conn, "LAST_INSERT_ID()", fontSize, fontFace, fontColor, moodId, bgColor, userId);
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException(
                        "conn.setAutoCommit(true),conn.close(), adding pblogtopics exception", e2);
            }
            throw new BaseDaoException("conn.rollback() error, adding pblogtopics, attributes", e1);
        }
    }
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("conn.commit() error, adding pblogtopics, attributes", e3);
    }

    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException("conn.close() error, adding pblogtopics, setAutoCommit(true) ", e4);
    }

    if (!RegexStrUtil.isNull(usertags)) {
        try {
            conn = ds.getConnection();
            tidResult = getTidQuery.run(conn, userId);
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException("conn.close() exception for getTidQuery()", e2);
            }
            throw new BaseDaoException("conn.close exeception for getTidQuery()", e);
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e2) {
            throw new BaseDaoException("connection close exception for getTidQuery() ", e2);
        }

        if (tidResult != null && tidResult.size() > 0) {
            addTagsAndNp(((Blog) tidResult.get(0)).getValue(DbConstants.TID), userId, usertags, userLogin);
        }
    }

    Fqn fqn = cacheUtil.fqn(DbConstants.PBLOG_TOPIC_LIST);
    if (treeCache.exists(fqn, userId)) {
        treeCache.remove(fqn, userId);
    }

    fqn = cacheUtil.fqn(DbConstants.PBLOG_DAILY_LIST);
    if (treeCache.exists(fqn, userId)) {
        treeCache.remove(fqn, userId);
    }

    fqn = cacheUtil.fqn(DbConstants.PERSONAL_BLOG);
    if (treeCache.exists(fqn, userId)) {
        treeCache.remove(fqn, userId);
    }

    fqn = cacheUtil.fqn(DbConstants.POPULAR_BLOGS);
    if (treeCache.exists(fqn, DbConstants.POPULAR_BLOG_KEY)) {
        treeCache.remove(fqn, DbConstants.POPULAR_BLOG_KEY);
    }

    fqn = cacheUtil.fqn(DbConstants.RECENT_BLOGS);
    if (treeCache.exists(fqn, DbConstants.RECENT_BLOG_KEY)) {
        treeCache.remove(fqn, DbConstants.RECENT_BLOG_KEY);
    }
    fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
    if (treeCache.exists(fqn, userLogin)) {
        treeCache.remove(fqn, userLogin);
    }

    fqn = cacheUtil.fqn(DbConstants.PBLOG_C_TOPICS);
    if (treeCache.exists(fqn, DbConstants.PBLOG_C_TOPICS)) {
        treeCache.remove(fqn, DbConstants.PBLOG_C_TOPICS);
    }
    fqn = cacheUtil.fqn(DbConstants.PBLOG_C_BIZ_TOPICS);
    if (treeCache.exists(fqn, DbConstants.PBLOG_C_BIZ_TOPICS)) {
        treeCache.remove(fqn, DbConstants.PBLOG_C_BIZ_TOPICS);
    }
}

From source file:backtype.storm.scheduler.adaptive.DataManager.java

public int checkTopology(String stormId) throws Exception {
    Connection connection = null;
    Statement statement = null;//from w ww  .ja  va 2 s .co  m
    ResultSet resultSet = null;
    int id = -1;
    logger.debug("Going to check topology " + stormId);
    try {
        connection = getConnection();
        connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        connection.setAutoCommit(false);
        statement = connection.createStatement();

        String sql = "select id from topology where storm_id = '" + stormId + "'";
        logger.debug("SQL query: " + sql);
        resultSet = statement.executeQuery(sql);
        if (resultSet.next()) {
            id = resultSet.getInt(1);
            logger.debug("Topology found, id: " + id);
        } else {
            logger.debug("Topology not found, let's create it");
            resultSet.close();
            sql = "insert into topology(storm_id) values('" + stormId + "')";
            logger.debug("SQL script: " + sql);
            statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            logger.debug("Retrieving generated id...");
            resultSet = statement.getGeneratedKeys();
            if (resultSet.next()) {
                id = resultSet.getInt(1);
                logger.debug("Ok, id: " + id);
            } else {
                throw new Exception("Cannot retrieve generated key");
            }
        }

        connection.commit();

    } catch (Exception e) {
        connection.rollback();
        logger.error("An error occurred checking a topology", e);
        throw e;
    } finally {
        if (resultSet != null)
            resultSet.close();
        if (statement != null)
            statement.close();
        if (connection != null)
            connection.close();
    }
    return id;
}

From source file:com.autentia.tnt.bill.migration.BillToBillPaymentMigration.java

/**
 * executes an script received by parameter
 * @param script the script to be launched
 *///  ww w  . ja v  a 2 s .c om
private static void executeScript(String script) throws Exception {
    Connection con = null;
    Statement stmt = null;
    LineNumberReader file = null;
    String delimiter = ";";

    try {
        log.debug("LOADING DATABASE SCRIPT" + script);

        // connect to database
        Class.forName(DATABASE_DRIVER);
        con = DriverManager.getConnection(DATABASE_CONNECTION, DATABASE_USER, DATABASE_PASS); //NOSONAR
        con.setAutoCommit(false); // DATABASE_PASS es nula
        stmt = con.createStatement();

        // load file
        InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script);
        if (sqlScript == null) {
            throw new FileNotFoundException(script);
        }
        file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8"));

        // Add batched SQL sentences to statement
        StringBuilder sentence = new StringBuilder();
        String line;
        while ((line = file.readLine()) != null) {
            line = line.trim();
            if (!line.startsWith("--")) {
                // Interpret "DELIMITER" sentences
                if (line.trim().toUpperCase(Locale.ENGLISH).startsWith("DELIMITER")) {
                    delimiter = line.trim().substring("DELIMITER".length()).trim();
                } else {
                    // Add line to sentence
                    if (line.endsWith(delimiter)) {
                        // Remove delimiter
                        String lastLine = line.substring(0, line.length() - delimiter.length());

                        // Append line to sentence
                        sentence.append(lastLine);

                        // Execute sentence
                        log.debug(" " + sentence.toString());
                        stmt.addBatch(sentence.toString());

                        // Prepare new sentence
                        sentence = new StringBuilder();
                    } else {
                        // Append line to sentence
                        sentence.append(line);

                        // Append separator for next line
                        sentence.append(" ");
                    }
                }
            }
        }

        // Execute batch
        log.debug("upgradeDatabase - executing batch of commands");
        stmt.executeBatch();

        // Commit transaction
        log.debug("upgradeDatabase - commiting changes to database");
        con.commit();

        // Report end of migration
        log.debug("END LOADING DATABASE SCRIPT");

    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }

    } finally {
        cierraFichero(file);
        liberaConexion(con, stmt, null);
    }
}

From source file:jade.domain.DFDBKB.java

/**
 * Removes a registration from the database.
 * @param convID id for the subscription
 * @return <code>true</code> if an entry has been found and removed  
 * - otherwise <code>false</code>
 *//* w w w . j a va 2s.  c  om*/
private boolean deregisterSubscription(String convID) throws SQLException {

    Connection conn = getConnectionWrapper().getConnection();
    try {
        PreparedStatements pss = getPreparedStatements();
        pss.stm_delSubscription.setString(1, convID);
        int rowCount = pss.stm_delSubscription.executeUpdate();
        conn.commit();
        return (rowCount != 0);
    } catch (SQLException sqle) {
        // Rollback the transaction
        try {
            conn.rollback();
        } catch (SQLException se) {
            logger.log(Logger.SEVERE, "Rollback for incomplete un-subscription failed.", se);
        }
        // Re-throw the exception
        throw sqle;
    }
}

From source file:com.wso2telco.dep.mediator.dao.ProvisionDAO.java

public void provisionServiceOperatorEntry(String operatorEndpoint, Integer provisionServiceId,
        String operatorName) throws SQLException, Exception {

    Connection con = null;
    PreparedStatement insertStatement = null;
    PreparedStatement updateStatement = null;

    try {/* ww  w .  j a  va 2 s  . c o m*/

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);

        if (con == null) {

            throw new Exception("Connection not found");
        }

        /**
         * Set autocommit off to handle the transaction
         */
        con.setAutoCommit(false);

        StringBuilder queryString = new StringBuilder("INSERT INTO ");
        queryString.append(DatabaseTables.PROVISION_SERVICE_OPERATOR_ENDPOINTS.getTableName());
        queryString.append(" (provision_service_did, domainurl, operator) ");
        queryString.append("VALUES (?, ?, ?)");

        insertStatement = con.prepareStatement(queryString.toString());

        insertStatement.setInt(1, provisionServiceId);
        insertStatement.setString(2, operatorEndpoint);
        insertStatement.setString(3, operatorName);

        log.debug("sql query in provisionServiceOperatorEntry : " + insertStatement);

        insertStatement.executeUpdate();

        StringBuilder updateQueryString = new StringBuilder("UPDATE ");
        updateQueryString.append(DatabaseTables.PROVISION_SERVICE_ENTRY.getTableName());
        updateQueryString.append(" SET is_active = ?");
        updateQueryString.append(" WHERE provision_service_did = ?");

        updateStatement = con.prepareStatement(updateQueryString.toString());

        updateStatement.setInt(1, 1);
        updateStatement.setInt(2, provisionServiceId);

        log.debug("sql query in provisionServiceOperatorEntry : " + updateStatement);

        updateStatement.executeUpdate();

        /**
         * commit the transaction if all success
         */
        con.commit();
    } catch (SQLException e) {

        /**
         * rollback if Exception occurs
         */
        con.rollback();

        log.error("database operation error in provisionServiceOperatorEntry : ", e);
        throw e;
    } catch (Exception e) {

        /**
         * rollback if Exception occurs
         */
        con.rollback();

        log.error("error in provisionServiceOperatorEntry : ", e);
        throw e;
    } finally {

        DbUtils.closeAllConnections(insertStatement, con, null);
        DbUtils.closeAllConnections(updateStatement, null, null);
    }
}

From source file:com.hangum.tadpole.rdb.core.editors.table.TableViewerEditPart.java

/**
 * Create contents of the editor part./*w  w  w . j  a  v  a  2  s.  co  m*/
 * @param parent
 */
@Override
public void createPartControl(Composite parent) {
    GridLayout gl_parent = new GridLayout(1, false);
    gl_parent.marginHeight = 0;
    parent.setLayout(gl_parent);

    composite = new Composite(parent, SWT.NONE);
    composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    composite.setLayout(new GridLayout(1, false));

    toolBar = new ToolBar(composite, SWT.FLAT | SWT.RIGHT);
    toolBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    tltmSave = new ToolItem(toolBar, SWT.NONE);
    tltmSave.setEnabled(false);
    tltmSave.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            // save ? .
            java.sql.Connection javaConn = null;
            Statement stmt = null;
            String lastExeQuery = ""; //$NON-NLS-1$

            try {
                SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
                javaConn = client.getDataSource().getConnection();

                // sqlite? forward cursor ?   
                stmt = javaConn.createStatement();//ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                javaConn.setAutoCommit(false);

                String[] querys = SQLTextUtil.delLineChar(getChangeQuery()).split(";"); //$NON-NLS-1$
                for (int i = 0; i < querys.length; i++) {

                    //   logger.info("exe query [" + querys[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$

                    lastExeQuery = querys[i];
                    stmt.execute(querys[i]);
                }

                javaConn.commit();

                // ??    .
                tltmSave.setEnabled(false);
                initBusiness(textWhere.getText());
                isDirty = false;

            } catch (Exception ee) {
                try {
                    if (javaConn != null)
                        javaConn.rollback();
                } catch (SQLException roE) {
                }
                ;

                logger.error(Messages.TableViewerEditPart_7, ee);

                // ?   .
                MessageDialog.openError(null, Messages.TableViewerEditPart_3, "Query [ " + lastExeQuery
                        + Messages.TableViewerEditPart_10 + ee.getMessage() + Messages.TableViewerEditPart_11); //$NON-NLS-2$

            } finally {
                // connection? ? ? .
                try {
                    javaConn.setAutoCommit(true);
                } catch (Exception ee) {
                }

                try {
                    if (stmt != null)
                        stmt.close();
                } catch (Exception ee) {
                }
                try {
                    if (javaConn != null)
                        javaConn.close();
                } catch (Exception ee) {
                }
            }

        }
    });
    tltmSave.setText(Messages.TableEditPart_0);

    tltmInsert = new ToolItem(toolBar, SWT.NONE);
    tltmInsert.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (modifyType == TABLE_MOD_TYPE.EDITOR)
                insertRow();
        }
    });
    tltmInsert.setText(Messages.TableEditPart_tltmInsert_text);
    tltmInsert.setEnabled(false);

    tltmDelete = new ToolItem(toolBar, SWT.NONE);
    tltmDelete.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {

            IStructuredSelection is = (IStructuredSelection) sqlResultTableViewer.getSelection();
            if (!is.isEmpty()) {
                deleteRow(is.getFirstElement());
            }

        }
    });
    tltmDelete.setEnabled(false);
    tltmDelete.setText(Messages.TableEditPart_1);

    tltmTablecomment = new ToolItem(toolBar, SWT.NONE);
    tltmTablecomment.setText(TbUtils.NONE_MSG);

    Composite compositeBody = new Composite(parent, SWT.NONE);
    compositeBody.setLayout(new GridLayout(2, false));
    compositeBody.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    Label lblWhere = new Label(compositeBody, SWT.NONE);
    lblWhere.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblWhere.setText(Messages.TableEditPart_lblWhere_text);

    textWhere = new Text(compositeBody, SWT.BORDER);
    textWhere.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.keyCode == SWT.Selection)
                changeWhere(textWhere.getText());
        }
    });
    textWhere.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    Label lblNewLabel = new Label(compositeBody, SWT.NONE);
    lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblNewLabel.setText(Messages.TableEditPart_3);

    textFilter = new Text(compositeBody, SWT.BORDER);
    textFilter.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.keyCode == SWT.Selection)
                setFilter();
        }
    });
    textFilter.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    sqlResultTableViewer = new TableViewer(compositeBody, SWT.VIRTUAL | SWT.BORDER | SWT.FULL_SELECTION);
    sqlResultTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            if (primaryKeyListIndex.size() >= 1)
                tltmDelete.setEnabled(true);
        }
    });
    tableResult = sqlResultTableViewer.getTable();
    tableResult.setHeaderVisible(true);
    tableResult.setLinesVisible(true);
    tableResult.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));

    // table markup-enable
    tableResult.setData(RWT.MARKUP_ENABLED, Boolean.TRUE);

    sqlFilter.setTable(tableResult);

    initBusiness(StringUtils.trimToEmpty(textWhere.getText()));
}

From source file:com.wso2telco.dep.mediator.dao.SMSMessagingDAO.java

/**
 * Insert sms request ids./*  ww  w  .ja v a  2s  . c  o m*/
 *
 * @param requestID
 *            the request id
 * @param senderAddress
 *            the sender address
 * @param pluginRequestIDs
 *            the plugin request i ds
 * @return true, if successful
 * @throws Exception
 */
public void insertSMSRequestIds(String requestId, String senderAddress, Map<String, String> gatewayRequestIds)
        throws SQLException, Exception {

    Connection con = null;
    PreparedStatement ps = null;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);

        /**
         * Set autocommit off to handle the transaction
         */
        con.setAutoCommit(false);

        StringBuilder queryString = new StringBuilder("INSERT INTO ");
        queryString.append(DatabaseTables.SEND_SMS_REQID.getTableName());
        queryString.append(" (hub_requestid, sender_address, delivery_address, plugin_requestid) ");
        queryString.append("VALUES (?, ?, ?, ?)");

        ps = con.prepareStatement(queryString.toString());

        for (Map.Entry<String, String> entry : gatewayRequestIds.entrySet()) {

            ps.setString(1, requestId);
            ps.setString(2, senderAddress);
            ps.setString(3, entry.getKey());
            ps.setString(4, entry.getValue());

            ps.addBatch();
        }

        log.debug("sql query in insertSMSRequestIds : " + ps);

        ps.executeBatch();

        /**
         * commit the transaction if all success
         */
        con.commit();
    } catch (SQLException e) {

        /**
         * rollback if Exception occurs
         */
        con.rollback();

        log.error("database operation error in insertSMSRequestIds : ", e);
        throw e;
    } catch (Exception e) {

        /**
         * rollback if Exception occurs
         */
        con.rollback();

        log.error("error in insertSMSRequestIds : ", e);
        throw e;
    } finally {

        DbUtils.closeAllConnections(ps, con, null);
    }
}

From source file:dbcount.DbCountInitializeJob.java

private int populateAccess(final Connection conn) throws SQLException {
    final Random random = new Random();

    final int PROBABILITY_PRECISION = 100; // 1 / 100
    final int NEW_PAGE_PROBABILITY = 15; // 15 / 100

    // Pages in the site :
    final String[] pages = { "/a", "/b", "/c", "/d", "/e", "/f", "/g", "/h", "/i", "/j" };
    // linkMatrix[i] is the array of pages(indexes) that page_i links to.
    final int[][] linkMatrix = { { 1, 5, 7 }, { 0, 7, 4, 6, }, { 0, 1, 7, 8 }, { 0, 2, 4, 6, 7, 9 }, { 0, 1 },
            { 0, 3, 5, 9 }, { 0 }, { 0, 1, 3 }, { 0, 2, 6 }, { 0, 2, 6 } };

    int totalPageview = 0;
    PreparedStatement statement = null;
    try {/*from w  w  w . j a  va 2 s  .  c om*/
        statement = conn.prepareStatement("INSERT INTO Access(url, referrer, time) VALUES (?, ?, ?)");

        int currentPage = random.nextInt(pages.length);
        String referrer = null;

        final int time = random.nextInt(50) + 50;
        for (int i = 0; i < time; i++) {
            statement.setString(1, pages[currentPage]);
            if (referrer == null) {
                statement.setNull(2, Types.VARCHAR);
            } else {
                statement.setString(2, referrer);
            }
            statement.setLong(3, i);
            statement.execute();
            ++totalPageview;

            // go to a new page with probability NEW_PAGE_PROBABILITY /
            // PROBABILITY_PRECISION
            int action = random.nextInt(PROBABILITY_PRECISION);
            if (action < NEW_PAGE_PROBABILITY) {
                currentPage = random.nextInt(pages.length); // a random page
                referrer = null;
            } else {
                referrer = pages[currentPage];
                action = random.nextInt(linkMatrix[currentPage].length);
                currentPage = linkMatrix[currentPage][action];
            }
        }

        conn.commit();

    } catch (SQLException ex) {
        conn.rollback();
        throw ex;
    } finally {
        if (statement != null) {
            statement.close();
        }
    }
    return totalPageview;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

/**
 * This method is the execution base. It depends on the execution type
 *
 * @param sql the SQL sentence to execute
 * @param params the parameters for the query
 * @param executionType type of the execution
 * //  www.  j  a  v  a 2  s. c o  m
 * @return the result of the query execution
 * @throws Exception if some error occurred
 */
private Object executeBase(String sql, String[] params, ExecutionType executionType) throws Exception {
    Exception error = null;

    Object result = null;

    Connection connection = null;
    PreparedStatement preparedStmnt = null;

    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        preparedStmnt = connection.prepareStatement(sql);
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                String param = params[i];
                preparedStmnt.setString(i + 1, param);
            }
        }
        result = executePreparedStatement(preparedStmnt, executionType);

        connection.commit();
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        if (connection != null) {
            try {
                if (error != null) {
                    connection.rollback();
                }
            } catch (SQLException se) {
                log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
            }
            try {
                connection.close();
            } catch (SQLException se) {
                log.warn("Se produjo un error al intentar cerrar la conexin: "
                        .concat(se.getLocalizedMessage()));
            }
        }
    }

    if (error != null) {
        throw error;
    }
    return result;
}

From source file:com.webpagebytes.wpbsample.database.WPBDatabase.java

public User createUser(User user) throws SQLException {
    Connection connection = getConnection();
    PreparedStatement statementUser = null;
    PreparedStatement statementAccount = null;
    try {// w  w  w  .ja va2 s  .  c  o  m
        statementUser = connection.prepareStatement(CREATE_USER_STATEMENT);
        connection.setAutoCommit(false);

        statementUser.setString(1, user.getUserName());
        statementUser.setString(2, user.getEmail());
        statementUser.setString(3, user.getPassword());
        java.sql.Timestamp sqlDate = new java.sql.Timestamp(user.getOpen_date().getTime());
        statementUser.setTimestamp(4, sqlDate);
        statementUser.setInt(5, user.getReceiveNewsletter());
        statementUser.setInt(6, user.getConfirmEmailFlag());
        statementUser.setString(7, user.getConfirmEmailRandom());
        java.sql.Timestamp sqlDate1 = new java.sql.Timestamp(user.getConfirmEmailDate().getTime());
        statementUser.setTimestamp(8, sqlDate1);
        statementUser.execute();

        ResultSet rs = statementUser.getGeneratedKeys();
        if (rs.next()) {
            int id = rs.getInt(1);
            user.setId(id);
        }
        statementAccount = connection.prepareStatement(CREATE_ACCOUNT_STATEMENT);
        statementAccount.setInt(1, user.getId());
        statementAccount.setLong(2, 0L);
        statementAccount.execute();
        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            connection.rollback();
        }
        throw e;
    } finally {
        if (statementUser != null) {
            statementUser.close();
        }
        if (statementAccount != null) {
            statementAccount.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
    return user;
}