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:com.cloudera.sqoop.TestIncrementalImport.java

/**
 * Insert rows with id = [low, hi) into tableName.
 */// w  w w  .  j  av a 2s.c o m
private void insertIdRows(String tableName, int low, int hi) throws SQLException {
    SqoopOptions options = new SqoopOptions();
    options.setConnectString(SOURCE_DB_URL);
    HsqldbManager manager = new HsqldbManager(options);
    Connection c = manager.getConnection();
    PreparedStatement s = null;
    try {
        s = c.prepareStatement("INSERT INTO " + tableName + " VALUES(?)");
        for (int i = low; i < hi; i++) {
            s.setInt(1, i);
            s.executeUpdate();
        }

        c.commit();
    } finally {
        s.close();
    }
}

From source file:net.codjo.dataprocess.server.treatmenthelper.TreatmentHelper.java

public static void initRepository(Connection con, List<RepositoryDescriptor> repositoryDescList)
        throws Exception {
    try {//w  w w . j av a  2s  .com
        con.setAutoCommit(false);

        LOG.info("Ajout des rfrentiels de traitement suivants :");
        for (RepositoryDescriptor repositoryDesc : repositoryDescList) {
            deleteRepository(con, repositoryDesc.getRepositoryId());
            insertAllRepositoryContent(con, repositoryDesc.getRepositoryId(),
                    repositoryDesc.getRepositoryName(), repositoryDesc.getRepositoryPath());
            insertRepository(con, repositoryDesc.getRepositoryId(), repositoryDesc.getRepositoryName());
        }
        List<TreatmentFragment> treatmentFragmentList = checkIntegrityRepositoryContent(con);
        if (!treatmentFragmentList.isEmpty()) {
            String message = " est trop long ! : ";
            int maxLength = maxLengthTreatmentId(treatmentFragmentList) + message.length() + LENGTH;
            StringBuilder errorMessage = new StringBuilder();
            errorMessage.append("\n").append(StringUtils.repeat("#", maxLength));
            errorMessage.append("\n").append(StringUtils.repeat("+", maxLength));
            for (TreatmentFragment treatmentFragment : treatmentFragmentList) {
                errorMessage.append("\n").append(treatmentFragment.getTreatmentId()).append(message)
                        .append(treatmentFragment.getContentFragment());
            }
            errorMessage.append("\n").append(StringUtils.repeat("+", maxLength));
            errorMessage.append("\n").append(StringUtils.repeat("#", maxLength));
            throw new TreatmentException(errorMessage.toString());
        } else {
            con.commit();
            LOG.info("Ajout termin avec succs !");
        }
    } catch (Exception ex) {
        con.rollback();
        LOG.error("\nErreur durant l'ajout des rfrentiels de traitement.\n!!! Rollback effectu !!!\n", ex);
        throw ex;
    } finally {
        con.setAutoCommit(true);
    }
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.internal.jdbc.JDBCInternalStorage.java

/**
 * Adds the supplied user to the internal storage.
 * @see IInternalStorage#add(ProvisioningUser)
 *///from w  w w  . j  av  a  2  s. co m
public void add(ProvisioningUser user) throws UserException {
    Connection oConnection = null;
    try {
        oConnection = _oDataSource.getConnection();
        oConnection.setAutoCommit(false);

        insertAccount(oConnection, user);

        Set<String> setMethods = user.getAuthenticationMethods();
        for (String sMethod : setMethods)
            insertProfile(oConnection, user, sMethod);

        oConnection.commit();
    } catch (UserException e) {
        rollback(oConnection);
        throw e;
    } catch (Exception e) {
        rollback(oConnection);
        _logger.fatal("Could not store", e);
        throw new UserException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (oConnection != null)
                oConnection.close();
        } catch (Exception e) {
            _logger.error("Could not close connection", e);
        }
    }
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProgramMessageSymbolSqlAdapter.java

public ProgramMessageSymbol deleteProgramMessageSymbol(int id) throws AdaptationException {
    ProgramMessageSymbol pmt = null;/* w ww .j a  va2  s.  c om*/
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        String query = "SELECT * FROM ProgramMessageSymbols " + "WHERE id = " + id;

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            String msg = "Attempt to delete program message type " + "failed.";
            log.error(msg);
            ;
            throw new AdaptationException(msg);
        }

        pmt = getProgramMessageSymbol(resultSet);
        query = "DELETE FROM ProgramMessageSymbols " + "WHERE id = " + id;

        statement.executeUpdate(query);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in deleteProgramMessageSymbol";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return pmt;
}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

private static void OverSpeedRecordsStoreIntoDB(Map<String, PtmOverSpeed> overSpeedRecords,
        ApplicationContext context) {//from  w  w w . ja va 2s. c o m
    Connection conn = null;
    String sql = "";
    try {

        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClient1");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = overSpeedRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            PtmOverSpeed pos = overSpeedRecords.get(key);
            sql = "insert into ALARMOVERSPEED_REA "
                    + " (CODE,LICENSE,LICENSECOLOR,BEGINTIME,ENDTIME,AVGSPEED,MAXSPEED,FLAG,BUSINESSTYPE) "
                    + " values (" + "'" + pos.getCode() + "'," + "'" + pos.getLicense() + "'," + "'"
                    + pos.getLicenseColor() + "'," + "'" + pos.getBeginTime() + "'," + "'" + pos.getEndTIme()
                    + "'," + pos.getAvgSpeed() + "," + pos.getMaxSpeed() + "," + pos.getFlag() + ","
                    + pos.getBusinessType() + ")";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB OverSpeed success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        overSpeedRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:eionet.acl.PersistenceDB.java

private void close(Connection con, Statement stmt, ResultSet rset) throws SQLException {
    try {/*  ww  w. j  av  a 2 s .  co m*/
        if (rset != null) {
            rset.close();
        }
        if (stmt != null) {
            stmt.close();
            if (!con.getAutoCommit()) {
                con.commit();
            }
        }
    } catch (Exception e) {
        throw new SQLException("Error" + e.getMessage());
    } finally {
        try {
            con.close();
        } catch (SQLException e) {
            throw new SQLException("Error" + e.getMessage());
        }
    }
}

From source file:net.riezebos.thoth.configuration.persistence.ThothDB.java

protected void performUpgrades(Connection connection) throws SQLException, IOException, DDLException {

    int latestVersion = determineCurrentVersion();
    int currentVersion = latestVersion;

    try (SqlStatement commentStmt = new SqlStatement(connection, getQuery("get_schema_version")); //
            ResultSet rs = commentStmt.executeQuery()) {
        if (rs.next()) {
            currentVersion = rs.getInt(1);
        }/*from   w ww.j  a v a2s . c  om*/
    }

    DatabaseIdiom idiom = DatabaseIdiomFactory.getDatabaseIdiom(connection);
    DDLExecuter executer = new DDLExecuter(connection, idiom);

    for (int i = currentVersion + 1; i <= latestVersion; i++) {
        LOG.info("Upgrading schema to version " + i);
        String upgradeScript = UPGRADE_SCRIPT_PREFIX + String.format("%03d", i) + ".ddl";
        executer.execute(upgradeScript);
        connection.commit();
    }
}

From source file:com.novartis.opensource.yada.QueryManager.java

/**
 * This method attempts (and usually suceeds) to close all JDBC resources
 * opened during processing of the current request, including
 * {@link ResultSet}s {@link java.sql.PreparedStatement}s and
 * {@link java.sql.CallableStatement}s using the utility methods in
 * {@link com.novartis.opensource.yada.ConnectionFactory}
 * /*from  ww w.  j  a va  2s .c om*/
 * @throws YADAConnectionException
 *           when there is a problem closing any of the resources
 * @see ConnectionFactory#releaseResources(ResultSet)
 * @see ConnectionFactory#releaseResources(java.sql.Statement)
 */
public void releaseResources() throws YADAConnectionException {
    for (String source : this.deferredCommits) {
        try {
            Connection connection = (Connection) this.connectionMap.get(source);
            connection.commit();
            String msg = "\n------------------------------------------------------------\n";
            msg += "   Commit successful on [" + source + "].\n";
            msg += "------------------------------------------------------------\n";
            l.info(msg);
        } catch (SQLException e) {
            String msg = "\n------------------------------------------------------------\n";
            msg += "   Unable to commit transaction on [" + source + "].\n";
            msg += "------------------------------------------------------------\n";
            l.error(msg); //TODO should there be a rollback message here?
        }
    }
    for (YADAQuery yq : this.getQueries()) {
        YADAQueryResult yqr = yq.getResult();
        if (yqr != null && yqr.getResults() != null) {
            for (Object result : yqr.getResults()) {
                if (result instanceof ResultSet) {
                    ConnectionFactory.releaseResources((ResultSet) result);
                }
            }
        }
        if (yq.getPstmt() != null && yq.getPstmt().size() > 0) {
            for (PreparedStatement p : yq.getPstmt()) {
                ConnectionFactory.releaseResources(p);
                l.debug("PreparedStatement removed from map.");
            }
        }
        if (yq.getPstmtForCount() != null && yq.getPstmtForCount().values().size() > 0) {
            for (PreparedStatement p : yq.getPstmtForCount().values()) {
                ConnectionFactory.releaseResources(p);
            }
        }
        if (yq.getCstmt() != null && yq.getCstmt().size() > 0) {
            for (CallableStatement c : yq.getCstmt()) {
                ConnectionFactory.releaseResources(c);
            }
        }
    }
    this.connectionMap.clear();
    l.debug("QueryManager connection map has been cleared.");
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.MoteDeploymentConfigurationSqlAdapter.java

public MoteDeploymentConfiguration deleteMoteDeploymentConfiguration(int id) throws AdaptationException {
    MoteDeploymentConfiguration mdc = null;
    Connection connection = null;
    Statement statement = null;/*  w ww. j  a va  2 s  .  c o  m*/
    ResultSet resultSet = null;

    try {
        String query = "SELECT * FROM MoteDeploymentConfigurations " + "WHERE id = " + id;

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            String msg = "Unable to select config to delete.";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        mdc = getMoteDeploymentConfiguration(resultSet);
        query = "DELETE FROM MoteDeploymentConfigurations " + "WHERE id = " + id;

        statement.executeUpdate(query);
        connection.commit();

    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in deleteMoteDeploymentConfiguration";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return mdc;
}

From source file:net.gcolin.simplerepo.search.SearchController.java

public void add(Model model, ResultType type) throws SQLException {
    Connection connection = null;
    try {/*w  w w.j a  v a  2 s.co m*/
        connection = datasource.getConnection();
        connection.setAutoCommit(false);
        Long versionId = new QueryRunner().query(connection,
                "select v.id from artifactversion v inner join artifact a on a.id = v.artifact_id "
                        + "where a.groupId = ? and a.artifactId = ? and v.version = ?",
                getLong, model.getGroupId(), model.getArtifactId(), model.getVersion());
        new QueryRunner().update(connection,
                "insert into artifacttype(version_id,packaging,classifier) VALUES (?,?,?)", versionId,
                type.getName(), type.getClassifier());
        connection.commit();
    } catch (SQLException ex) {
        connection.rollback();
        throw ex;
    } finally {
        DbUtils.close(connection);
    }
}