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.autentia.tnt.bill.migration.support.OriginalInformationRecoverer.java

/**
 * Recupera la fecha de pago o cobro de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura/*  w ww  .j av a2  s  . c  o m*/
 */
public static Date[] getFechaFacturaOriginal(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    Date[] result = new Date[0];

    try {
        log.info("RECOVERING FECHAS " + billType + " ORIGINALES");

        // 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 vacia
        String sql = "SELECT date_add(creationDate, INTERVAL expiration DAY) as date FROM Bill B where billType = ? order by date";
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);
        rs = pstmt.executeQuery();

        rs.last();
        result = new Date[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDate(1);
            log.info("\t" + result[counter]);
            counter++;
        }
        con.commit();
    } 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.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java

/**
 * Recupera la suma total de todos los conceptos de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura/* www  .  ja  va  2s  .com*/
 */
public static double[] getImporteFacturaMigrated(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    double[] result = new double[0];

    try {
        log.info("RECOVERING IMPORTE 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 vacio         

        String sql = "SELECT bp.amount FROM BillPayment bp, Bill b where bp.billId = b.id and b.billType = ? order by amount";

        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);
        rs = pstmt.executeQuery();

        rs.last();
        result = new double[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDouble(1);
            log.info("\t" + result[counter]);
            counter++;
        }

    } 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:gridool.db.partitioning.monetdb.MonetDBCopyIntoOperation.java

@Override
public Serializable execute() throws SQLException {
    final Connection conn;
    try {//www .j a v  a  2s.  co  m
        conn = getConnection();
    } catch (ClassNotFoundException e) {
        LOG.error(e);
        throw new SQLException(e.getMessage());
    }
    if (createTableDDL != null) {// prepare a table
        try {
            JDBCUtils.update(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 File loadFile = prepareLoadFile(tableName, rowsData);
    this.rowsData = null;
    final String query = complementCopyIntoQuery(copyIntoQuery, loadFile);
    try {
        JDBCUtils.update(conn, query);
        conn.commit();
    } catch (SQLException e) {
        LOG.error("rollback a transaction", e);
        conn.rollback();
        throw e;
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            LOG.debug(e);
        }
        if (!loadFile.delete()) {
            LOG.warn("Could not remove a tempolary file: " + loadFile.getAbsolutePath());
        }
    }

    return Boolean.TRUE;
}

From source file:com.wabacus.system.dataset.update.action.rationaldb.AbsRationalDBUpdateAction.java

public void rollbackTransaction(ReportRequest rrequest) {
    Connection conn = rrequest.getConnection(this.datasource);
    try {/* ww w.  j  ava 2s.c  o  m*/
        if (conn.getAutoCommit())
            return;
        conn.rollback();
        conn.setAutoCommit(true);
    } catch (SQLException e) {
        throw new WabacusRuntimeException(
                "" + this.ownerUpdateBean.getOwner().getReportBean().getPath() + "??"
                        + this.datasource + "",
                e);
    }
}

From source file:com.anyuan.thomweboss.persistence.jdbcimpl.user.UserDaoJdbcImpl.java

@Override
public boolean saveAll(List<User> entities) {

    if (null != entities) {
        Connection conn = getConnection();
        try {//from  w  w  w  .j a va2 s .c  o m
            conn.setAutoCommit(false);
            for (User user : entities) {
                save(user);
            }
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }

    }

    return super.saveAll(entities);
}

From source file:com.mnt.base.das.DBFactory.java

public void endTransaction() {

    TransactionOwner to = toHolder.get();

    if (to.decressDeep()) {
        Connection conn = to.connection;

        try {/*w  ww .jav  a 2 s.  c  om*/
            conn.commit();
        } catch (SQLException e) {
            log.error("Fail to commit the transaction, auto rollback.", e);

            try {
                conn.rollback();
            } catch (SQLException e1) {
                log.error("Fail to rollback the transaction.", e1);
                throw new RuntimeException("End transaction error: fail to rollback the transaction.", e1);
            }
        }

        try {
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            log.error("fail to set connection auto commit as true after the transacation.", e);
            throw new RuntimeException("end transaction error: fail to set connection auto commit as true.", e);
        }

        close(conn);

        toHolder.remove();
    }
}

From source file:com.netflix.metacat.usermetadata.mysql.MySqlTagService.java

private void remove(final QualifiedName name, final Set<String> tags, final boolean updateUserMetadata) {
    try {// w  w w. java 2  s .  c o m
        final Connection conn = getDataSource().getConnection();
        try {
            remove(conn, name, tags, updateUserMetadata);
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    } catch (SQLException e) {
        final String message = String.format("Failed to remove tags for name %s", name);
        log.error(message, e);
        throw new UserMetadataServiceException(message, e);
    }
}

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

public Project deleteProject(int projectID) throws AdaptationException {
    Project project = null;//from w ww .j a v a2 s  .  co  m
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

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

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

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

        project = getProject(resultSet);
        query = "DELETE FROM Projects WHERE id = " + projectID;

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

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

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

public ProgramSymbol deleteProgramSymbol(int id) throws AdaptationException {
    ProgramSymbol programSymbol = null;/*from  w  ww.  ja v a2  s  . c  o m*/
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

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

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

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

        programSymbol = getProgramSymbol(resultSet);
        query = "DELETE FROM ProgramSymbols " + "WHERE id = " + id;

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

        String msg = "SQLException in deleteProgramSymbol";
        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:gridool.db.sql.ParallelSQLExecJob.java

private static void createMergeView(@Nonnull final Connection conn, @Nonnull final String ddl,
        @Nonnull final ReadWriteLock rwlock) throws GridException {
    if (LOG.isInfoEnabled()) {
        LOG.info("Create a merge view: \n" + ddl);
    }//from   w  w w  .  j  av a  2 s  . co  m
    final Lock wlock = rwlock.writeLock();
    try {
        wlock.lock();
        JDBCUtils.update(conn, ddl);
    } catch (SQLException e) {
        String errmsg = "failed running a reduce query: " + ddl;
        LOG.error(errmsg, e);
        try {
            conn.rollback();
        } catch (SQLException rbe) {
            LOG.warn("Rollback failed", rbe);
        }
        throw new GridException(errmsg, e);
    } finally {
        wlock.unlock();
    }
}