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.globalsight.ling.tm3.core.TuStorage.java

/**
 * Deletes one or more TUs, along with all their TUVs, attributes, and
 * history./* w  w  w. j  a v  a 2 s.co  m*/
 * 
 * @param ids
 *            List of TU ids to delete
 * @throws SQLException
 */
public void deleteTusById(List<Long> ids) throws SQLException {
    if (ids.size() == 0) {
        return;
    }
    Connection conn = null;
    try {
        conn = DbUtil.getConnection();
        conn.setAutoCommit(false);
        SQLUtil.exec(conn, new StatementBuilder().append("DELETE FROM ").append(storage.getTuTableName())
                .append(" WHERE id IN ").append(SQLUtil.longGroup(ids)));
        conn.commit();
    } catch (Exception e) {
        throw new SQLException(e);
    } finally {
        DbUtil.silentReturnConnection(conn);
    }
}

From source file:mercury.DigitalMediaDAO.java

public final Integer uploadToDigitalMedia(FileItem file) {
    Connection con = null;
    Integer serial = 0;/*  ww w.  j ava 2 s  .  c  o m*/
    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:edu.clemson.cs.nestbed.server.adaptation.sql.ProgramSymbolSqlAdapter.java

public ProgramSymbol createNewProgramSymbol(int programID, String module, String symbol, int address, int size)
        throws AdaptationException {
    ProgramSymbol programSymbol = null;//from  ww w. j av  a 2  s  . c  o  m
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        String query = "INSERT INTO ProgramSymbols " + "(programID, module, symbol, address, size)"
                + " VALUES (" + programID + ", '" + module + "',  '" + symbol + "', " + address + ", " + size
                + ")";

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

        query = "SELECT * FROM ProgramSymbols WHERE  " + "programID =  " + programID + "  AND "
                + "module    = '" + module + "' AND " + "symbol    = '" + symbol + "'";

        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to create program symbol failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        programSymbol = getProgramSymbol(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in createNewProgramSymbol";
        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 programSymbol;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.C3PREmbeddedTomcatTestBase.java

/**
 * See http://sourceforge.net/tracker/index.php?func=detail&aid=1459205&
 * group_id=47439&atid=449491. We will execute PURGE RECYCLEBIN here.
 * /*w  w w .ja v  a 2 s  .  com*/
 * @throws Exception
 * @throws SQLException
 */
private void purgeRecycleBin() throws SQLException, Exception {
    Connection conn = null;
    Statement st = null;
    try {
        conn = getConnection().getConnection();
        st = conn.createStatement();
        st.execute("PURGE RECYCLEBIN");
    } catch (Exception e) {
        logger.warning(
                "Unable to execute PURGE RECYCLEBIN either because of an error or because not running on Oracle: "
                        + e.getMessage());
    } finally {
        try {
            st.close();
        } catch (Exception e) {
            logger.warning("Coult not close the Statement. Probably, safe to ignore.");
        }
        try {
            conn.commit();
        } catch (Exception e) {
            logger.warning("Coult not commit the Connection. Probably, safe to ignore.");
        }
        try {
            conn.close();
        } catch (Exception e) {
            logger.warning("Coult not close the Connection. Probably, safe to ignore.");
        }
    }
}

From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java

/**
 * Execute query with no result.//from w  w w  .  j  a va 2 s.c o m
 *
 * @param query the query
 * @param giveException throws any exception generated if true, 
 *       if false all exceptions are consumed
 * @throws Exception if giveException is true and their is an error executing
 *       the query
 */
public void executeQueryNoResult(String query, boolean giveException) throws Exception {
    Connection con = null;
    Statement stmt = null;
    SQLException exc = null;
    try {
        con = this.getConnection();
        con.setAutoCommit(false);
        stmt = con.createStatement();
        stmt.execute(query);
        con.commit();
    } catch (SQLException e) {
        if (!giveException) {
            if (log.isErrorEnabled()) {
                log.error(query, e);
            }
        }

        if (con != null) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                if (log.isErrorEnabled()) {
                    log.error("Error during rollback.", e1);
                }
            }
        }
        if (giveException) {
            exc = e;
        }
    } finally {
        try {
            if (con != null && !con.isClosed()) {
                con.setAutoCommit(true);
                con.close();
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error("Error during close.", e);
            }
        }
        if (exc != null && giveException) {
            throw exc;
        }
    }
}

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

public ProjectDeploymentConfiguration createNewProjectDeploymentConfig(int projectID, String name,
        String description) throws AdaptationException {

    ProjectDeploymentConfiguration config = null;
    Connection connection = null;
    Statement statement = null;/*from  www. j  ava2  s .  c o m*/
    ResultSet resultSet = null;

    try {
        String query = "INSERT INTO ProjectDeploymentConfigurations" + "(projectID, name, description) VALUES ("
                + projectID + ", '" + name + "', '" + description + "')";

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

        query = "SELECT * FROM ProjectDeploymentConfigurations WHERE " + " projectID   = " + projectID
                + "  AND " + " name        = '" + name + "' AND " + " description = '" + description + "'";

        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to create " + "ProjectDeploymentConfiguration failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        config = getProjectDeploymentConfiguration(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in createNewProjectDeploymentConfig";
        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 config;
}

From source file:chh.utils.db.source.common.JdbcClient.java

public void executeInsertQuery(String query, List<List<Column>> columnLists) {
    Connection connection = null;
    try {/*from w ww.j a va  2  s.  c  o m*/
        connection = connectionProvider.getConnection();
        boolean autoCommit = connection.getAutoCommit();
        if (autoCommit) {
            connection.setAutoCommit(false);
        }

        LOG.debug("Executing query {}", query);

        PreparedStatement preparedStatement = connection.prepareStatement(query);
        if (queryTimeoutSecs > 0) {
            preparedStatement.setQueryTimeout(queryTimeoutSecs);
        }

        for (List<Column> columnList : columnLists) {
            setPreparedStatementParams(preparedStatement, columnList);
            preparedStatement.addBatch();
        }

        int[] results = preparedStatement.executeBatch();
        if (Arrays.asList(results).contains(Statement.EXECUTE_FAILED)) {
            connection.rollback();
            throw new RuntimeException(
                    "failed at least one sql statement in the batch, operation rolled back.");
        } else {
            try {
                connection.commit();
            } catch (SQLException e) {
                throw new RuntimeException("Failed to commit insert query " + query, e);
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException("Failed to execute insert query " + query, e);
    } finally {
        closeConnection(connection);
    }
}

From source file:com.wso2telco.dep.operatorservice.dao.BlackListWhiteListDAO.java

/**
 * blacklist list given msisdns/*  w  w w. ja  va2s. c  o  m*/
 *
 * @param msisdns
 * @param apiID
 * @param apiName
 * @param userID
 * @throws Exception
 */
public void blacklist(MSISDNValidationDTO msisdns, final String apiID, final String apiName,
        final String userID) throws Exception {

    log.debug("BlackListWhiteListDAO.blacklist triggerd MSISDN["
            + StringUtils.join(msisdns.getValidProcessed().toArray(), ",") + "] apiID:" + apiID + " apiName:"
            + apiName + " userID:" + userID);

    StringBuilder sql = new StringBuilder();
    sql.append(" INSERT INTO ");
    sql.append(OparatorTable.BLACKLIST_MSISDN.getTObject());
    sql.append("(PREFIX,MSISDN,API_ID,API_NAME,USER_ID,VALIDATION_REGEX)");
    sql.append(" VALUES (?, ?, ?, ?, ?, ?)");

    Connection conn = null;
    PreparedStatement ps = null;

    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB);
        ps = conn.prepareStatement(sql.toString());

        conn.setAutoCommit(false);

        for (MsisdnDTO msisdn : msisdns.getValidProcessed()) {

            ps.setString(1, msisdn.getPrefix());
            ps.setString(2, msisdn.getDigits());
            ps.setString(3, apiID);
            ps.setString(4, apiName);
            ps.setString(5, userID);
            ps.setString(6, msisdns.getValidationRegex());
            ps.addBatch();
        }

        ps.executeBatch();
        conn.commit();

    } catch (Exception e) {
        if (conn != null) {
            conn.rollback();
        }
        throw e;
    } finally {
        DbUtils.closeAllConnections(ps, conn, null);
    }

}

From source file:com.wso2telco.dep.operatorservice.dao.BlackListWhiteListDAO.java

/**
 * when the subscription id is known//from  w  w w.  j av  a  2s. c  o m
 *
 * @param userMSISDNs
 * @param subscriptionId
 * @param apiID
 * @param applicationID
 * @throws SQLException
 * @throws Exception
 */
public void whitelist(MSISDNValidationDTO msisdns, String subscriptionId, String apiID, String applicationID)
        throws Exception {

    StringBuilder sql = new StringBuilder();
    sql.append("INSERT INTO ");
    sql.append(OparatorTable.SUBSCRIPTION_WHITELIST.getTObject());
    sql.append(" (subscriptionID, prefix, msisdn, api_id, application_id, validation_regex)");
    sql.append(" VALUES (?,?,?,?,?,?);");

    Connection conn = null;
    PreparedStatement ps = null;

    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB);
        ps = conn.prepareStatement(sql.toString());

        conn.setAutoCommit(false);
        for (MsisdnDTO msisdn : msisdns.getValidProcessed()) {

            ps.setString(1, subscriptionId);
            ps.setString(2, msisdn.getPrefix());
            ps.setString(3, msisdn.getDigits());
            ps.setString(4, apiID);
            ps.setString(5, applicationID);
            ps.setString(6, msisdns.getValidationRegex());

            ps.addBatch();
        }
        ps.executeBatch();
        conn.commit();

    } catch (Exception e) {
        if (conn != null) {
            conn.rollback();
        }
        log.error("", e);
        throw e;
    } finally {
        DbUtils.closeAllConnections(ps, conn, null);
    }

}

From source file:localdomain.localhost.CasInitializer.java

@ManagedOperation
public void changeUserPassword(@NotNull String username, @NotNull String clearTextPassword) {
    Connection cnn = null;
    PreparedStatement stmt = null;
    try {/*  ww  w .ja  va  2s  .  co m*/
        cnn = dataSource.getConnection();
        cnn.setAutoCommit(false);
        stmt = cnn.prepareStatement(
                "update `" + tableUsers + "` set `" + fieldPassword + "` = ? where `" + fieldUser + "` like ?");
        stmt.setString(1, passwordEncoder.encode(clearTextPassword));
        stmt.setString(2, username);
        int rowCount = stmt.executeUpdate();
        if (rowCount == 0) {
            throw new NoSuchElementException("No user '" + username + "' found");
        } else if (rowCount == 1) {
            logger.info("Password of user '" + username + "' was updated");
        } else {
            new IllegalArgumentException(
                    "More (" + rowCount + ") than 1 row deleted for username '" + username + "', rollback");
        }
        logger.info("User '" + username + "' deleted");
        cnn.commit();
    } catch (RuntimeException e) {
        rollbackQuietly(cnn);
        String msg = "Exception changing password for user '" + username + "': " + e;
        logger.warn(msg, e);
        throw new RuntimeException(msg);
    } catch (SQLException e) {
        rollbackQuietly(cnn);
        String msg = "Exception changing password for user '" + username + "': " + e;
        logger.warn(msg, e);
        throw new RuntimeException(msg);
    } finally {
        closeQuietly(cnn, stmt);
    }
}