Example usage for java.sql Connection commit

List of usage examples for java.sql Connection commit

Introduction

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

Prototype

void commit() throws SQLException;

Source Link

Document

Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.

Usage

From source file:azkaban.project.JdbcProjectLoader.java

@Override
public void updateProjectProperty(Project project, Props props) throws ProjectManagerException {
    Connection connection = getConnection();
    try {/*from  w  ww  . java2s .c om*/
        updateProjectProperty(connection, project, props.getSource(), props);
        connection.commit();
    } catch (SQLException e) {
        throw new ProjectManagerException("Error uploading project property files", e);
    } catch (IOException e) {
        throw new ProjectManagerException("Error uploading project property file", e);
    } finally {
        DbUtils.closeQuietly(connection);
    }
}

From source file:Classes.Database.java

/**
 * Makes a save SQL statement and executes it
 *
 * @param sql       The query, use an "?" at the place of a input. Like this:
 *                  INSERT INTO TABLE('name', 'lastname' , enz ) VALUES(?,?, enz);
 * @param arguments The arguments correspont to same questionmark.
 * @return The generated key/* w w w .j  a  v  a  2  s  .co m*/
 * @throws SQLException
 */
public Integer setDatabase(String sql, Object... arguments) {
    Connection conn = null;
    PreparedStatement psta = null;
    ResultSet rs = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(url, username, password);
        psta = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        EscapeSQL(psta, arguments);

        psta.executeUpdate();
        rs = psta.getGeneratedKeys();
        if (rs != null && rs.next()) {
            if (rs.getInt(1) == 0) { //maybe errors
                return -1;
            }
            return rs.getInt(1);
        }
        return -1;
    } catch (SQLException e) {
        Logger.getAnonymousLogger().log(Level.WARNING, "SQL Error: " + e.getMessage(), e);
        return -1;
    } catch (ClassNotFoundException e) {
        Logger.getAnonymousLogger().log(Level.WARNING, "Class Error " + e.getMessage(), e);
        return -1;
    } finally {
        if (conn != null) {
            //close and commit
            Logger.getAnonymousLogger().log(Level.INFO, "Commit" + sql);
            try {
                conn.commit();
            } catch (SQLException e) {
                Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage(), e);
            }
            try {
                conn.close();
            } catch (SQLException e) {
                Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage(), e);
            }
        }

        if (psta != null) {
            try {
                psta.close();
            } catch (SQLException e) {
                Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage(), e);
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage(), e);
            }
        }
    }
}

From source file:azkaban.project.JdbcProjectLoader.java

@Override
public void uploadFlow(Project project, int version, Flow flow) throws ProjectManagerException {
    logger.info("Uploading flows");
    Connection connection = getConnection();

    try {//  w ww .j  a v  a  2 s  .c o  m
        uploadFlow(connection, project, version, flow, defaultEncodingType);
        connection.commit();
    } catch (IOException e) {
        throw new ProjectManagerException("Flow Upload failed.", e);
    } catch (SQLException e) {
        throw new ProjectManagerException("Flow Upload failed commit.", e);
    } finally {
        DbUtils.closeQuietly(connection);
    }
}

From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO.java

/**
 * Read a ExtendedFieldValue in persistent storage.
 * @param aConnection an open connection to the HarvestDatabase
 * @param aExtendedFieldValue The ExtendedFieldValue to update
 * @param aCommit Should we commit this or not
 * @throws SQLException In case of database problems.
 *//*from   w  w  w  .  ja  v  a2  s .co  m*/
public void update(Connection aConnection, ExtendedFieldValue aExtendedFieldValue, boolean aCommit)
        throws SQLException {
    PreparedStatement statement = null;
    final Long extendedfieldvalueId = aExtendedFieldValue.getExtendedFieldID();
    if (!exists(aConnection, extendedfieldvalueId)) {
        throw new UnknownID(
                "Extended Field Value id " + extendedfieldvalueId + " is not known in persistent storage");
    }

    aConnection.setAutoCommit(false);

    statement = aConnection.prepareStatement(
            "" + "UPDATE extendedfieldvalue " + "SET    extendedfield_id = ?, " + "       instance_id = ?, "
                    + "       content = ? " + "WHERE  extendedfieldvalue_id = ? and instance_id = ?");

    statement.setLong(1, aExtendedFieldValue.getExtendedFieldID());
    statement.setLong(2, aExtendedFieldValue.getInstanceID());
    statement.setString(3, aExtendedFieldValue.getContent());
    statement.setLong(4, aExtendedFieldValue.getExtendedFieldValueID());
    statement.setLong(5, aExtendedFieldValue.getInstanceID());

    statement.executeUpdate();

    if (aCommit) {
        aConnection.commit();
    }
}

From source file:com.cloudera.sqoop.manager.SqlManager.java

@Override
public void migrateData(String fromTable, String toTable) throws SQLException {
    release(); // Release any previous ResultSet
    String updateQuery = "INSERT INTO " + toTable + " ( SELECT * FROM " + fromTable + " )";

    String deleteQuery = "DELETE FROM " + fromTable;
    Statement stmt = null;//from  w  ww . j  ava2s .  c  o  m
    try {
        Connection conn = getConnection();
        stmt = conn.createStatement();

        // Insert data from the fromTable to the toTable
        int updateCount = stmt.executeUpdate(updateQuery);
        LOG.info("Migrated " + updateCount + " records from " + fromTable + " to " + toTable);

        // Delete the records from the fromTable
        int deleteCount = stmt.executeUpdate(deleteQuery);

        // If the counts do not match, fail the transaction
        if (updateCount != deleteCount) {
            conn.rollback();
            throw new RuntimeException("Inconsistent record counts");
        }
        conn.commit();
    } catch (SQLException ex) {
        LOG.error("Unable to migrate data from " + fromTable + " to " + toTable, ex);
        throw ex;
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                LOG.error("Unable to close statement", ex);
            }
        }
    }
}

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

public void moUssdSubscriptionEntry(List<OperatorSubscriptionDTO> domainsubs, Integer moSubscriptionId)
        throws SQLException, Exception {

    Connection con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
    PreparedStatement insertStatement = null;

    try {//  ww w  . j a va2s.  c  om

        if (con == null) {
            throw new Exception("Connection not found");
        }
        con.setAutoCommit(false);

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

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

        for (OperatorSubscriptionDTO d : domainsubs) {

            insertStatement.setInt(1, moSubscriptionId);
            insertStatement.setString(2, d.getDomain());
            insertStatement.setString(3, d.getOperator());

            insertStatement.addBatch();
        }

        insertStatement.executeBatch();
        con.commit();

    } catch (SQLException e) {

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

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

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

From source file:com.che.software.testato.domain.dao.jdbc.impl.ActivityDAO.java

/**
 * Creates the documentation of an activity from actions and parameters
 * lists.//from w  w w  . j  a  v  a2  s. c o  m
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param activity the activity to document.
 * @param actions the actions list.
 * @param parameters the parameters list.
 * @since July, 2011.
 * @throws ActivityDocumentationCreationDAOException if an error occurs
 *         during the creation.
 */
@Override
public void createActivityDocumentation(Activity activity, List<ActivityAction> actions,
        List<ActivityParameter> parameters) throws ActivityDocumentationCreationDAOException {
    LOGGER.debug("createActivityDocumentation(" + activity.getActivityId() + "," + actions.size() + " actions,"
            + parameters.size() + " parameters).");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection, "UPDATE activity SET global_description = ? WHERE activity_id = ? ",
                new Object[] { activity.getGlobalDescription(), activity.getActivityId() });
        int cpt = 1;
        for (ActivityAction action : actions) {
            getQueryRunner().update(connection,
                    "INSERT INTO activity_action(activity_action_id, activity_id, description, result, \"order\") VALUES(nextval('activity_action_id_seq'),?,?,?,?) ",
                    new Object[] { activity.getActivityId(), action.getDescription(), action.getResult(),
                            cpt++ });
        }
        for (ActivityParameter parameter : parameters) {
            getQueryRunner().update(connection,
                    "INSERT INTO activity_parameter(activity_parameter_id, activity_id, name, description) VALUES(nextval('activity_parameter_id_seq'),?,?,?) ",
                    new Object[] { activity.getActivityId(), "{" + parameter.getName() + "}",
                            parameter.getDescription() });
        }
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new ActivityDocumentationCreationDAOException(e1);
        }
        throw new ActivityDocumentationCreationDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:azkaban.project.JdbcProjectLoader.java

@Override
public void uploadProjectFile(Project project, int version, String filetype, String filename, File localFile,
        String uploader) throws ProjectManagerException {
    logger.info("Uploading to " + project.getName() + " version:" + version + " file:" + filename);
    Connection connection = getConnection();

    try {//w  w w.  ja  v  a  2  s .c o  m
        uploadProjectFile(connection, project, version, filetype, filename, localFile, uploader);
        connection.commit();
        logger.info("Commiting upload " + localFile.getName());
    } catch (SQLException e) {
        logger.error(e);
        throw new ProjectManagerException("Error getting DB connection.", e);
    } finally {
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.idea.IdeaDAO.java

@Override
public void updateIdea(IIdea idea) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {/* w ww .j a  v  a 2 s .co m*/
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(UPDATE_IDEA);
        int index = 1;
        stat.setString(index++, idea.getTitle());
        stat.setString(index++, idea.getDescr());
        stat.setInt(index++, idea.getStatus());
        stat.setInt(index++, idea.getVotePositive());
        stat.setInt(index++, idea.getVoteNegative());
        stat.setString(index++, idea.getInstanceCode());
        stat.setString(index++, idea.getId());
        stat.executeUpdate();

        this.updateTags(idea, conn);

        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error updating Idea {}", idea.getId(), t);
        throw new RuntimeException("Error updating Idea", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }
}

From source file:edu.umd.cs.submitServer.servlets.ImportProject.java

/**
 * The doPost method of the servlet. <br>
 * //from w  ww  .  ja va  2 s  .c o m
 * This method is called when a form has its tag value method equals to
 * post.
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    FileItem fileItem = null;
    boolean transactionSuccess = false;
    try {
        conn = getConnection();

        // MultipartRequestFilter is required
        MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
        Course course = (Course) request.getAttribute(COURSE);
        StudentRegistration canonicalStudentRegistration = StudentRegistration.lookupByStudentRegistrationPK(
                multipartRequest.getIntParameter("canonicalStudentRegistrationPK", 0), conn);

        fileItem = multipartRequest.getFileItem();

        conn.setAutoCommit(false);
        /*
         * 20090608: changed TRANSACTION_READ_COMMITTED to
         * TRANSACTION_REPEATABLE_READ to make transaction compatible with
         * innodb in MySQL 5.1, which defines READ_COMMITTED as unsafe for
         * use with standard binary logging. For more information, see:
         * <http
         * ://dev.mysql.com/doc/refman/5.1/en/set-transaction.html#isolevel_read
         * -committed>
         */
        conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        Project project = Project.importProject(fileItem.getInputStream(), course, canonicalStudentRegistration,
                conn);

        conn.commit();
        transactionSuccess = true;

        String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
        response.sendRedirect(redirectUrl);

    } catch (ClassNotFoundException e) {
        throw new ServletException(e);
    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
    }
}