Example usage for java.sql Connection getAutoCommit

List of usage examples for java.sql Connection getAutoCommit

Introduction

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

Prototype

boolean getAutoCommit() throws SQLException;

Source Link

Document

Retrieves the current auto-commit mode for this Connection object.

Usage

From source file:ips1ap101.lib.core.db.util.DB.java

public static boolean rollback(Connection connection) {
    if (connection != null) {
        try {// w  w  w .  j a  v  a2  s. c  om
            if (!connection.isClosed() && !connection.getAutoCommit()) {
                connection.rollback();
            }
            return true;
        } catch (SQLException ex) {
            Bitacora.logFatal(ex);
        }
    }
    return false;
}

From source file:org.jahia.utils.DatabaseUtils.java

public static int executeUpdate(String query) throws SQLException {
    int result = 0;
    Connection conn = null;
    Statement stmt = null;/*w ww . java  2s .  c o m*/
    try {
        conn = getDatasource().getConnection();
        stmt = conn.createStatement();
        result = stmt.executeUpdate(query);
        if (!conn.getAutoCommit()) {
            conn.commit();
        }
    } catch (SQLException e) {
        if (conn != null && !conn.getAutoCommit()) {
            conn.rollback();
        }
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception e) {
                // ignore
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }

    return result;
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.dao.UploadedUsageFileInfoDAO.java

/**
 * Delete obsolete usage records in the db
 *
 * @param lastKeptDate up to which files should be retained
 * @throws UsagePublisherException//from   w  w  w  .  j  ava  2s.  com
 */
public static void deleteProcessedOldFiles(Date lastKeptDate) throws UsagePublisherException {
    Connection connection = null;
    PreparedStatement delStatement = null;
    boolean autoCommitStatus = false;
    try {
        connection = APIMgtDBUtil.getConnection();
        autoCommitStatus = connection.getAutoCommit();
        connection.setAutoCommit(false);
        delStatement = connection
                .prepareStatement(MicroGatewayAPIUsageConstants.DELETE_OLD_UPLOAD_COMPLETED_FILES);
        delStatement.setTimestamp(1, new Timestamp(lastKeptDate.getTime()));
        delStatement.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException e1) {
            log.error("Error occurred while rolling back deleting old uploaded files transaction.", e1);
        }
        throw new UsagePublisherException("Error occurred while deleting old uploaded files.", e);
    } finally {
        try {
            connection.setAutoCommit(autoCommitStatus);
        } catch (SQLException e) {
            log.warn("Failed to reset auto commit state of database connection to the previous state.", e);
        }
        APIMgtDBUtil.closeAllConnections(delStatement, connection, null);
    }
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.dao.UploadedUsageFileInfoDAO.java

/**
 * Adds a record into the database with uploaded file's information
 *
 * @param dto   Uploaded File Information represented by {@link UploadedFileInfoDTO}
 * @param uploadedInputStream Input stream with the uploaded file content
 * @throws UsagePublisherException if there is an error while getting a connection or executing the query
 */// w  w  w .  jav  a2 s.c om
public static void persistFileUpload(UploadedFileInfoDTO dto, InputStream uploadedInputStream)
        throws UsagePublisherException {
    Connection connection = null;
    boolean autoCommitStatus = false;
    PreparedStatement statement = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        autoCommitStatus = connection.getAutoCommit();
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(MicroGatewayAPIUsageConstants.INSERT_UPLOADED_FILE_INFO_QUERY);
        statement.setString(1, dto.getTenantDomain());
        statement.setString(2, dto.getFileName());
        statement.setTimestamp(3, new Timestamp(dto.getTimeStamp()));
        statement.setBinaryStream(4, uploadedInputStream);
        statement.executeUpdate();
        connection.commit();
        if (log.isDebugEnabled()) {
            log.debug("Persisted Uploaded File info : " + dto.toString());
        }
    } catch (SQLException e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException e1) {
            log.error("Error occurred while rolling back inserting uploaded information into db transaction,",
                    e1);
        }
        throw new UsagePublisherException("Error occurred while inserting uploaded information into database",
                e);
    } finally {
        try {
            connection.setAutoCommit(autoCommitStatus);
        } catch (SQLException e) {
            log.warn("Failed to reset auto commit state of database connection to the previous state.", e);
        }
        APIMgtDBUtil.closeAllConnections(statement, connection, null);
    }
}

From source file:fll.db.NonNumericNominees.java

/**
 * Add a set of nominees to the database. If the nominee already exsts, there
 * is no error.//from   w  w  w. j  ava  2 s  .  c om
 * 
 * @throws SQLException
 */
public static void addNominees(final Connection connection, final int tournamentId, final String category,
        final Set<Integer> teamNumbers) throws SQLException {
    PreparedStatement check = null;
    ResultSet checkResult = null;
    PreparedStatement insert = null;
    final boolean autoCommit = connection.getAutoCommit();
    try {
        connection.setAutoCommit(false);

        check = connection.prepareStatement("SELECT team_number FROM non_numeric_nominees" //
                + " WHERE tournament = ?" //
                + "   AND category = ?" //
                + "   AND team_number = ?");
        check.setInt(1, tournamentId);
        check.setString(2, category);

        insert = connection.prepareStatement("INSERT INTO non_numeric_nominees" //
                + " (tournament, category, team_number) VALUES(?, ?, ?)");
        insert.setInt(1, tournamentId);
        insert.setString(2, category);

        for (final int teamNumber : teamNumbers) {
            check.setInt(3, teamNumber);
            insert.setInt(3, teamNumber);

            checkResult = check.executeQuery();
            if (!checkResult.next()) {
                insert.executeUpdate();
            }
        }

        connection.commit();
    } finally {
        connection.setAutoCommit(autoCommit);

        SQLFunctions.close(checkResult);
        SQLFunctions.close(check);
        SQLFunctions.close(insert);
    }
}

From source file:ips1ap101.lib.core.db.util.DB.java

public static boolean setAutoCommit(Connection connection, boolean autoCommit) {
    if (connection != null) {
        try {//ww w  . j  ava  2s. com
            if (!connection.isClosed()) {
                if (connection.getAutoCommit() == autoCommit) {
                    Bitacora.trace("autocommit is already " + autoCommit);
                } else {
                    Bitacora.trace("setting autocommit to " + autoCommit);
                    connection.setAutoCommit(autoCommit);
                }
                return true;
            }
        } catch (SQLException ex) {
            Bitacora.logFatal(ex);
        }
    }
    return false;
}

From source file:org.openconcerto.sql.utils.SQLUtils.java

/**
 * Execute <code>h</code> in a transaction. Only the outer most call to
 * <code>executeAtomic()</code> commit or roll back a transaction, for recursive calls if
 * <code>continueTx</code> is <code>true</code> then nothing happens, else a save point is
 * created and rolled back if an exception occurs (allowing the caller to catch the exception
 * without loosing the current transaction).
 * <p>/*from   ww w . java2  s .  c  o m*/
 * NOTE : if <code>continueTx</code> is <code>true</code> and an exception is thrown, the
 * connection might be aborted. So you should notify the caller, e.g. propagate the exception so
 * that he can roll back the transaction.
 * </p>
 * 
 * @param <T> type of return
 * @param <X> type of exception of <code>h</code>
 * @param ds the data source where h should be executed.
 * @param h the code to execute.
 * @param continueTx only relevant if already in a transaction : if <code>true</code> the
 *        handler will just be executed and the connection won't be modified (i.e. the existing
 *        transaction will neither be committed nor rolled back) ; if <code>false</code> a save
 *        point will be used.
 * @return what h returns.
 * @throws SQLException if a problem occurs.
 * @throws X if <code>h</code> throw it.
 */
public static <T, X extends Exception> T executeAtomic(final SQLDataSource ds,
        final ConnectionHandlerNoSetup<T, X> h, final boolean continueTx) throws SQLException, X {
    return ds.useConnection(new ConnectionHandler<T, X>() {

        private Boolean autoCommit = null;
        private Savepoint savePoint = null;

        @Override
        public boolean canRestoreState() {
            return true;
        }

        @Override
        public void setup(Connection conn) throws SQLException {
            this.autoCommit = conn.getAutoCommit();
            if (this.autoCommit) {
                conn.setAutoCommit(false);
            } else if (!continueTx) {
                this.savePoint = conn.setSavepoint();
            }
        }

        @Override
        public T handle(final SQLDataSource ds) throws X, SQLException {
            return h.handle(ds);
        }

        @Override
        public void restoreState(Connection conn) throws SQLException {
            // can be null if getAutoCommit() failed, in that case nothing to do
            final boolean hasStoppedAutoCommit = Boolean.TRUE.equals(this.autoCommit);
            final boolean hasSavePoint = this.savePoint != null;
            // at most one is enough (otherwise change if/else below)
            assert !(hasStoppedAutoCommit && hasSavePoint) : "Begun a transaction and created a save point";
            if (hasStoppedAutoCommit || hasSavePoint) {
                // true if the exception was thrown by get()
                boolean getExn = true;
                try {
                    this.get();
                    getExn = false;
                    if (hasStoppedAutoCommit)
                        conn.commit();
                    // MS SQL cannot release save points
                    // http://technet.microsoft.com/en-us/library/ms378791.aspx
                    else if (ds.getSystem() != SQLSystem.MSSQL)
                        conn.releaseSavepoint(this.savePoint);
                } catch (Exception e) {
                    if (hasStoppedAutoCommit)
                        conn.rollback();
                    else
                        conn.rollback(this.savePoint);
                    // if the exception wasn't generated by get() the caller must be notified
                    if (!getExn)
                        throw new SQLException("Couldn't " + (hasSavePoint ? "release save point" : "commit"),
                                e);
                } finally {
                    if (hasStoppedAutoCommit)
                        conn.setAutoCommit(true);
                }
            }
        }
    });
}

From source file:com.wso2telco.core.dbutils.DbUtils.java

/**
 * Close connection.//from w  w  w . j  a va2s  .  c  o m
 *
 * @param dbConnection
 *            the db connection
 */
private static void closeConnection(Connection dbConnection) {

    try {

        if (dbConnection != null && dbConnection.getAutoCommit() != true) {

            log.debug("database connection is active and auto commit is false");
            dbConnection.setAutoCommit(true);
            dbConnection.close();
            log.debug("database connection set to close and auto commit set to true");
        } else if (dbConnection != null) {

            log.debug("database connection is active");
            dbConnection.close();
            log.debug("database connection set to closed");
        }
    } catch (SQLException e) {

        log.error("database error. Could not close database connection. continuing with others. - "
                + e.getMessage(), e);
    }

}

From source file:gridool.db.helpers.GridDbUtils.java

@Nonnull
public static Connection getPrimaryDbConnection(final DBAccessor dba, boolean autoCommit) throws GridException {
    final Connection conn;
    try {/*  w w w. j  a  va  2s .c  om*/
        conn = dba.getPrimaryDbConnection();
        if (conn.getAutoCommit() != autoCommit) {
            conn.setAutoCommit(autoCommit);
        }
    } catch (SQLException e) {
        LOG.error(e);
        throw new GridException("failed connecting to the primary database: " + dba.getPrimaryDbName());
    }
    return conn;
}

From source file:com.wso2telco.dbutils.DbUtils.java

/**
 * Close connection.//from  www  . j  a  v  a 2 s. c  om
 *
 * @param dbConnection
 *            the db connection
 */
private static void closeConnection(Connection dbConnection) {

    try {

        if (dbConnection != null && dbConnection.getAutoCommit() != true) {

            log.debug("database connection is active and auto commit is false");
            dbConnection.setAutoCommit(true);
            dbConnection.close();
            log.debug("database connection set to close and auto commit set to true");
        } else if (dbConnection != null) {

            log.debug("database connection is active");
            dbConnection.close();
            log.debug("database connection set to closed");
        }
    } catch (SQLException e) {

        log.error("database error. Could not close database connection. continuing with others. - "
                + e.getMessage(), e);
    }

    /*
     * if (dbConnection != null) { try { dbConnection.close(); } catch
     * (SQLException e) { log.warn(
     * "Database error. Could not close database connection. Continuing with "
     * + "others. - " + e.getMessage(), e); } }
     */
}