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:com.mirth.connect.server.util.DatabaseUtil.java

public static void executeScript(List<String> script, boolean ignoreErrors) throws Exception {
    SqlSessionManager sqlSessionManger = SqlConfig.getSqlSessionManager();

    Connection conn = null;
    ResultSet resultSet = null;/*w  ww  . j  ava2  s  . co m*/
    Statement statement = null;

    try {
        sqlSessionManger.startManagedSession();
        conn = sqlSessionManger.getConnection();
        /*
         * Set auto commit to false or an exception will be thrown when trying to rollback
         */
        conn.setAutoCommit(false);
        statement = conn.createStatement();

        for (String statementString : script) {
            statementString = statementString.trim();
            if (statementString.length() > 0) {
                try {
                    statement.execute(statementString);
                    conn.commit();
                } catch (SQLException se) {
                    if (!ignoreErrors) {
                        throw se;
                    } else {
                        logger.error("Error was encountered and ignored while executing statement: "
                                + statementString, se);
                        conn.rollback();
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(conn);
        sqlSessionManger.close();
    }
}

From source file:com.migratebird.database.impl.DefaultSQLHandler.java

/**
 * Ends a transaction that was started using startTransaction
 * by rolling back and turning auto commit back on.
 *
 * @param dataSource The data source, not null
 *//*  www  .jav a 2 s  .c  om*/
public void endTransactionAndRollback(DataSource dataSource) {
    Connection connection = getConnection(dataSource);
    try {
        connection.rollback();

    } catch (Exception e) {
        throw new DatabaseException("Unable to perform database rollback.", e);
    } finally {
        reenableAutoCommit(connection);
    }
}

From source file:com.fileanalyzer.dao.impl.FilesDAOImpl.java

@Override
public void handleException(final Exception e, final Connection con) {
    if (con != null) {
        try {//from   w  w w.  j  a  v a 2 s  . c om
            log.error("Transaction is being rolled back", e);
            con.rollback();
        } catch (SQLException excep) {
            log.error(excep);
        }
    }
}

From source file:gridool.db.catalog.DistributionCatalog.java

private static boolean prepareTables(@Nonnull final Connection conn, final String distributionTableName,
        final boolean autoCommit) {
    final String ddl = "CREATE TABLE \"" + distributionTableName
            + "\"(distkey varchar(50) NOT NULL, node varchar(50) NOT NULL, masternode varchar(50), state SMALLINT NOT NULL);\n"
            + "CREATE TABLE \"" + partitionkeyTableName
            + "\"(tablename varchar(30) PRIMARY KEY, tplprefix varchar(20) NOT NULL, id " + tableIdSQLDataType
            + " auto_increment);";
    try {/*from  w  w w.  j  av a2 s  .  com*/
        JDBCUtils.update(conn, ddl);
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        // avoid table already exists error
        if (!autoCommit) {
            try {
                conn.rollback();
            } catch (SQLException sqle) {
                LOG.warn("failed to rollback", sqle);
            }
        }
        return false;
    }
    return true;
}

From source file:com.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java

/**
 * Recupera la suma total de todos los conceptos de todas las facturas del tipo que se envie por parametro
 * @param billType tipo de factura/*  w ww .  j a  v  a  2  s  .co m*/
 */
public static double getTotalFacturasMigrated(String billType) throws Exception {

    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    double result = -1;

    try {
        log.info("RECOVERING TOTAL FACTURAS " + billType + " MIGRADAS");

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

        String sql = "SELECT sum(bp.amount) FROM BillPayment bp, Bill b where bp.billId = b.id and b.billType = ?";
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);

        rs = pstmt.executeQuery();
        while (rs.next()) {
            result = rs.getDouble(1);
            log.info("\t" + result);
        }

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

    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}

From source file:com.bluexml.side.Integration.alfresco.sql.synchronization.common.JdbcTransactionListener.java

public void afterRollback() {
    Connection connection = getConnection();
    //      if (logger.isDebugEnabled())
    //         logger.debug("[afterRollback] on " + connection);
    try {/*from   w  w  w  .ja v a  2  s.  co m*/
        connection.rollback();
    } catch (SQLException e) {
        logger.error("[afterRollback]", e);
    } finally {
        if (logger.isDebugEnabled())
            logger.debug("[afterRollback] Releasing existing connection");
        releaseConnection(connection);
    }
}

From source file:org.spring.data.gemfire.app.dao.provider.JdbcUserDao.java

protected void rollback(final Connection connection) {
    if (connection != null) {
        try {//from   www .  jav a  2  s.c o m
            connection.rollback();
        } catch (SQLException e) {
            throw createDataAccessException("Failed to rollback the Connection!", e);
        }
    }
}

From source file:gridool.db.DBInsertOperation.java

public Serializable execute() throws SQLException, GridException {
    final Connection conn = getConnection();
    if (createTableDDL != null) {
        try {//w  ww .  jav  a 2 s  .  c  om
            executeDDL(conn, createTableDDL);
        } catch (SQLException e) {
            conn.rollback();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Table already exists. Try to truncate " + tableName, e);
            }
            truncateTable(conn, tableName);
            // fall through
        }
    }
    final String insertSql = constructQuery(tableName, fieldNames, records);
    try {
        executeInsertQuery(conn, insertSql, records);
        conn.commit();
    } catch (SQLException e) {
        LOG.error("rollback a transaction", e);
        conn.rollback();
        throw e;
    } finally {
        conn.close();
    }
    return Boolean.TRUE;
}

From source file:com.cyclopsgroup.tornado.hibernate.impl.DefaultHibernateService.java

/**
 * Overwrite or implement method rollbackTransaction()
 *
 * @see com.cyclopsgroup.tornado.hibernate.HibernateService#rollbackTransaction(java.lang.String)
 *///from w w  w.j  av  a2s .  com
public void rollbackTransaction(String dataSourceName) throws Exception {
    SessionWrapper wrapper = (SessionWrapper) localSession.get();
    if (wrapper != null) {
        Transaction transaction = wrapper.getTransaction(dataSourceName);
        if (transaction != null) {
            transaction.rollback();
        }
        Connection dbcon = wrapper.getConnection(dataSourceName);
        dbcon.rollback();
    }
}

From source file:com.migratebird.database.impl.DefaultSQLHandler.java

/**
 * Ends a transaction that was started using startTransaction
 * by committing and turning auto commit back on.
 *
 * @param dataSource The data source, not null
 *///from w  w  w . jav  a2 s  .  c  om
public void endTransactionAndCommit(DataSource dataSource) {
    Connection connection = getConnection(dataSource);
    try {
        connection.commit();

    } catch (Exception e) {
        try {
            connection.rollback();
        } catch (Exception t) {
            logger.warn("Unable to perform database rollback after commit failure.");
        }
        throw new DatabaseException("Error while performing database commit.", e);
    } finally {
        reenableAutoCommit(connection);
    }
}