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.alfaariss.oa.engine.user.provisioning.storage.internal.jdbc.JDBCInternalStorage.java

private void rollback(Connection oConnection) {
    if (oConnection != null) {
        try {//from   www.  j av a 2 s .  c  o  m
            oConnection.rollback();
        } catch (Exception e) {
            _logger.error("Could not rollback", e);
        }
    }
}

From source file:edu.ku.brc.specify.datamodel.DataModelObjBase.java

/**
 * Deletes the data object./*from  w ww  .j  a v a  2s  .  c  o  m*/
 * @param doShowError whether to show the an error dialog
 * @return true is ok, false if not
 */
public static boolean delete(final int id, final int tableId, final boolean doShowError) {
    errMsg = null;

    DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(tableId);
    Connection connection = DBConnection.getInstance().createConnection();
    Statement stmt = null;
    try {
        stmt = connection.createStatement();
        int numRecs = stmt
                .executeUpdate("DELETE FROM " + ti.getName() + " WHERE " + ti.getIdColumnName() + " = " + id);
        if (numRecs != 1) {
            // TODO need error message
            return false;
        }

    } catch (SQLException ex) {
        edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataModelObjBase.class, ex);
        ex.printStackTrace();
        errMsg = ex.toString();

        try {
            connection.rollback();

        } catch (SQLException ex2) {
            edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataModelObjBase.class, ex2);
            ex.printStackTrace();
        }
        return false;

    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataModelObjBase.class, ex);
            ex.printStackTrace();
        }
    }
    return true;
}

From source file:org.cfr.capsicum.datasource.CayenneTransactionManager.java

@Override
protected void doRollback(DefaultTransactionStatus status) {
    CayenneTransactionObject txObject = (CayenneTransactionObject) status.getTransaction();
    Connection con = txObject.getConnectionHolder().getConnection();
    ObjectContext dataContext = txObject.getConnectionHolderEx().getObjectContext();
    if (status.isDebug()) {
        logger.debug("Rolling back JDBC transaction on Connection [" + con + "]");
    }//from  w  w w.  ja va 2  s  .  c  om
    try {
        if (dataContext != null) {
            dataContext.rollbackChanges();
        }
        con.rollback();
    } catch (SQLException ex) {
        throw new TransactionSystemException("Could not commit JDBC transaction",
                exceptionTranslator.convertJdbcAccessException(ex));
    } catch (CayenneRuntimeException ex) {
        throw new TransactionSystemException("Could not commit JDBC transaction",
                exceptionTranslator.convertAccessException(ex));
    }
}

From source file:com.reydentx.core.client.MySQLClient.java

public int executeMultiQuery(List<String> listQuery) {
    Connection conn = borrowClient();
    if (conn == null) {
        return (-1);
    }//  ww w . j av  a 2  s  .  c o  m
    try {
        conn.setAutoCommit(false);
        for (String query : listQuery) {
            PreparedStatement ps = conn.prepareStatement(query);
            ps.execute();
        }
        conn.commit();
        returnObject(conn);
    } catch (SQLException sqlEx) {
        try {
            _logger.error("Rollback traction because ex:" + sqlEx.getMessage(), sqlEx);
            conn.rollback(); // must be innoDB
        } catch (SQLException sqlExRollback) {
            _logger.error(sqlExRollback.getMessage(), sqlExRollback);
        }
    } catch (Exception ex) {
        _logger.error(ex.getMessage(), ex);
        invalidClient(conn);
        return (-1);
    } finally {
        try {
            conn.setAutoCommit(true);
        } catch (Exception ex) {
            _logger.error(ex.getMessage(), ex);
        }
    }
    return 0;
}

From source file:net.firejack.platform.core.utils.db.DBUtils.java

private static void insertDataToTargetTable(TablesMapping mapping, Connection sourceConnection,
        Connection targetConnection) throws SQLException {
    Map<Column, Column> columnMapping = mapping.getColumnMapping();
    if (columnMapping.isEmpty()) {
        logger.warn("No columns are detected - no data to insert.");
    } else {/*from   ww w. j a  va2  s.c o m*/
        ResultSet rs = selectDataFromSource(sourceConnection, mapping);

        String insertQuery = populateInsertQuery(mapping);
        PreparedStatement insertStatement = targetConnection.prepareStatement(insertQuery);
        targetConnection.setAutoCommit(false);
        try {
            int currentStep = 1;
            while (rs.next()) {
                for (int i = 1; i <= columnMapping.size(); i++) {
                    insertStatement.setObject(i, rs.getObject(i));
                }
                insertStatement.addBatch();
                if (++currentStep > DEFAULT_BATCH_SIZE) {
                    insertStatement.executeBatch();
                    targetConnection.commit();
                    currentStep = 1;
                }
            }
            if (currentStep != 1) {
                insertStatement.executeBatch();
                targetConnection.commit();
            }
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            targetConnection.rollback();
        } finally {
            insertStatement.close();
            rs.close();
        }
    }
}

From source file:org.ulyssis.ipp.processor.Processor.java

private void trySpawnReaderListener(int readerId) {
    URI uri = Config.getCurrentConfig().getReader(readerId).getURI();
    String updateChannel = JedisHelper.dbLocalChannel(Config.getCurrentConfig().getUpdateChannel(), uri);
    try {/*  w w w  .j av a 2 s .  co  m*/
        Optional<Long> lastUpdate;
        {
            Connection connection = null;
            try {
                connection = Database.createConnection(EnumSet.of(READ_ONLY));
                lastUpdate = getLastUpdateForReader(connection, readerId);
                connection.commit();
            } catch (SQLException e) {
                if (connection != null)
                    connection.rollback();
                throw e;
            } finally {
                if (connection != null) {
                    connection.close();
                }
            }
        }
        Jedis subJedis = JedisHelper.get(uri);
        ReaderListener listener = new ReaderListener(readerId, this::queueEvent, lastUpdate);
        readerListeners.add(listener);
        Thread thread = new Thread(() -> {
            try {
                LOG.info("Reader listener {} subscribing to channel {} on uri {}", readerId, updateChannel,
                        uri);
                subJedis.subscribe(listener, updateChannel);
            } catch (JedisConnectionException e) {
                LOG.error(
                        "Reader listener {} stopped (uri: {}) because of a connection failure, scheduling reconnect",
                        readerId, uri, e);
                executorService.schedule(() -> trySpawnReaderListener(readerId), 5L, TimeUnit.SECONDS);
            }
        });
        threads.add(thread);
        thread.start();
    } catch (SQLException e) {
        LOG.error("Error fetching last update for reader {} from database, scheduling retry", readerId, e);
        executorService.schedule(() -> trySpawnReaderListener(readerId), 5L, TimeUnit.SECONDS);
    } catch (JedisConnectionException e) {
        LOG.error("Couldn't connect to reader {}, uri {}, scheduling reconnect", readerId, uri, e);
        executorService.schedule(() -> trySpawnReaderListener(readerId), 5L, TimeUnit.SECONDS);
    }
}

From source file:nl.strohalm.cyclos.struts.CyclosRequestProcessor.java

private void rollbackReadOnlyConnection(final HttpServletRequest request) {
    if (noTransaction(request)) {
        return;//w  ww. java  2 s  .  co m
    }
    final Connection connection = (Connection) TransactionSynchronizationManager
            .getResource(connectionProvider);
    try {
        logDebug(request, "Rolling back read-only transaction");
        connection.rollback();
    } catch (final SQLException e) {
        throw new IllegalStateException(e);
    }
}

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

@Override
public Void rename(final QualifiedName name, final String newTableName) {
    try {//from w  w  w.  ja v a2 s .co m
        final Connection conn = getDataSource().getConnection();
        try {
            final QualifiedName newName = QualifiedName.ofTable(name.getCatalogName(), name.getDatabaseName(),
                    newTableName);
            new QueryRunner().update(conn, SQL_UPDATE_TAG_ITEM, newName.toString(), name.toString());
            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    } catch (SQLException e) {
        final String message = String.format("Failed to rename item name %s", name);
        log.error(message, e);
        throw new UserMetadataServiceException(message, e);
    }
    return null;
}

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

public Program updateProgramPath(int id, String sourcePath) throws AdaptationException {
    Program program = null;//from  w w  w. j av a2  s  . c  o m
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        String query = "UPDATE Programs SET " + "sourcePath = '" + sourcePath + "' " + "WHERE id = " + id;

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

        query = "SELECT * from Programs WHERE id = " + id;
        resultSet = statement.executeQuery(query);

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

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

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

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static void close(Connection connection) {
    try {/*  www.j  a va 2s  . co m*/
        if (connection != null && !connection.isClosed()) {
            connection.rollback();
            connection.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}