Java Code Examples for java.sql.Connection.rollback()

The following are Jave code examples for showing how to use rollback() of the java.sql.Connection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Banmanager   File: Transaction.java   View Source Code Vote up 6 votes
public void execute(AbstractSqlTable table) {
    Connection connection;

    synchronized (connection = table.connection()) {
        try {
            connection.setAutoCommit(false);

            for (int i = 0; i < actions.size(); i++) {
                handlers.get(i).accept(actions.get(i).execute(table));
            }

            connection.commit();
            connection.setAutoCommit(true);
        } catch (SQLException e) {
            try {
                connection.rollback();
                connection.setAutoCommit(true);
            } catch (SQLException sqlException) {
                sqlException.printStackTrace();
            }
        }

    }
}
 
Example 2
Project: jdbc-middleware   File: ConnectionManager.java   View Source Code Vote up 6 votes
public void rollbackTransaction() {
    LOGGER.debug("Rolling back transaction");
    Connection connection = transactionConnection.get();
    if(connection == null) {
        throw new IllegalStateException("Unable to rollback transaction with missing connection");
    }
    try {
        connection.rollback();
        connection.close();
    }
    catch(SQLException e) {
        try {
            connection.close();
        }
        catch(SQLException e1) {
            throw new RuntimeException("Unable to close connection", e1);
        }
        throw new RuntimeException("Failed to rollback transaction", e);
    }
    finally {
        transactionConnection.remove();
    }
}
 
Example 3
Project: ralasafe   File: BackupManagerImpl.java   View Source Code Vote up 6 votes
public Backup addBackup(Backup backup) throws EntityExistException {
	backup.setId(newBackupId());
	Connection conn = null;
	try {
		conn = DBPower.getConnection(table.getId());
		conn.setAutoCommit(false);
		backup.setCreateTime(new Date());
		saver.save(conn, backup);
		importBackup(conn, backup);
		conn.commit();
	} catch (SQLException e) {
		log.error( "", e );
		try {
			conn.rollback();
		} catch (SQLException e1) {
			log.error( "", e1 );
			throw new RalasafeException(e1);
		}
	} finally {
		DBUtil.close(conn);
	}

	return backup;
}
 
Example 4
Project: aliyun-maxcompute-data-collectors   File: OracleManager.java   View Source Code Vote up 6 votes
/**
 * @return a Connection instance that can be used to connect to the
 * given database, if a previously-opened connection is available in
 * the cache. Returns null if none is available in the map.
 */
public synchronized Connection getConnection(String connectStr,
    String username) throws SQLException {
  CacheKey key = new CacheKey(connectStr, username);
  Connection cached = connectionMap.get(key);
  if (null != cached) {
    connectionMap.remove(key);
    if (cached.isReadOnly()) {
      // Read-only mode? Don't want it.
      cached.close();
    }

    if (cached.isClosed()) {
      // This connection isn't usable.
      return null;
    }

    cached.rollback(); // Reset any transaction state.
    cached.clearWarnings();

    LOG.debug("Got cached connection for " + key);
  }

  return cached;
}
 
Example 5
Project: DBus   File: OracleManager.java   View Source Code Vote up 6 votes
/**
 * @return a Connection instance that can be used to connect to the
 * given database, if a previously-opened connection is available in
 * the cache. Returns null if none is available in the map.
 */
public synchronized Connection getConnection(String connectStr,
    String username) throws SQLException {
  CacheKey key = new CacheKey(connectStr, username);
  Connection cached = connectionMap.get(key);
  if (null != cached) {
    connectionMap.remove(key);
    if (cached.isReadOnly()) {
      // Read-only mode? Don't want it.
      cached.close();
    }

    if (cached.isClosed()) {
      // This connection isn't usable.
      return null;
    }

    cached.rollback(); // Reset any transaction state.
    cached.clearWarnings();

    LOG.debug("Got cached connection for " + key);
  }

  return cached;
}
 
Example 6
Project: Nird2   File: TransactionIsolationTest.java   View Source Code Vote up 5 votes
@Test
public void testLockTimeoutOnRowWithMvcc() throws Exception {
	Connection connection = openConnection(true);
	try {
		createTableAndInsertRow(connection);
	} finally {
		connection.close();
	}
	// Start the first transaction
	Connection txn1 = openConnection(true);
	try {
		txn1.setAutoCommit(false);
		// The first transaction should read the initial value
		assertEquals(123, getCounter(txn1));
		// Start the second transaction
		Connection txn2 = openConnection(true);
		try {
			txn2.setAutoCommit(false);
			// The second transaction should read the initial value
			assertEquals(123, getCounter(txn2));
			// The first transaction updates the value but doesn't commit it
			assertEquals(1, setCounter(txn1, 234));
			// The second transaction tries to update the value
			try {
				setCounter(txn2, 345);
				fail();
			} catch (SQLException expected) {
				// Expected: the row is locked by the first transaction
			}
			// Abort the transactions
			txn1.rollback();
			txn2.rollback();
		} finally {
			txn2.close();
		}
	} finally {
		txn1.close();
	}
}
 
Example 7
Project: OpenDiabetes   File: TriggerSample.java   View Source Code Vote up 5 votes
private static void doSomeWork() throws SQLException {

        Connection conn = getConnection();
        Statement  stmt = conn.createStatement();

        conn.setAutoCommit(false);
        stmt.execute("INSERT INTO trig_test VALUES (1, 'hello')");
        stmt.execute("INSERT INTO trig_test VALUES (2, 'now what?')");
        stmt.execute("INSERT INTO trig_test VALUES (3, 'unchangable')");
        stmt.execute("INSERT INTO trig_test VALUES (4, 'goodbye')");
        conn.commit();
        dumpTable("trig_test");
        stmt.execute("UPDATE trig_test SET value = 'all done'");
        conn.commit();
        dumpTable("trig_test");
        stmt.execute("DELETE FROM trig_test");
        conn.rollback();
        dumpTable("trig_test");

        try {
            stmt.execute("INSERT INTO trig_test VALUES(11, 'whatever')");
        } catch (SQLException se) {
            se.printStackTrace();
        }

        stmt.execute("INSERT INTO trig_test VALUES(10, 'whatever')");
        conn.commit();
        dumpTable("trig_test");
        stmt.close();
        conn.close();
    }
 
Example 8
Project: aliyun-maxcompute-data-collectors   File: Db2Manager.java   View Source Code Vote up 5 votes
@Override
public String[] listDatabases() {
  Connection conn = null;
  ResultSet rset = null;
  List<String> databases = new ArrayList<String>();
  try {
    conn = getConnection();
    rset = conn.getMetaData().getSchemas();
    while (rset.next()) {
      // The ResultSet contains two columns - TABLE_SCHEM(1),
      // TABLE_CATALOG(2). We are only interested in TABLE_SCHEM which
      // represents schema name.
      databases.add(rset.getString(1));
    }
    conn.commit();
  } catch (SQLException sqle) {
    try {
      if (conn != null) {
        conn.rollback();
      }
    } catch (SQLException ce) {
      LoggingUtils.logAll(LOG, "Failed to rollback transaction", ce);
    }
    LoggingUtils.logAll(LOG, "Failed to list databases", sqle);
    throw new RuntimeException(sqle);
  } finally {
    if (rset != null) {
      try {
        rset.close();
      } catch (SQLException re) {
        LoggingUtils.logAll(LOG, "Failed to close resultset", re);
      }
    }
  }

  return databases.toArray(new String[databases.size()]);
}
 
Example 9
Project: morf   File: SqlScriptExecutor.java   View Source Code Vote up 5 votes
private void commitOrRollback(Connection connection, SqlExceptionThrowingRunnable runnable) throws SQLException {
  try {
    runnable.run();
    connection.commit();
  } catch (Exception e) {
    connection.rollback();
    throw e;
  }
}
 
Example 10
Project: scorekeeperfrontend   File: PostgresqlDatabase.java   View Source Code Vote up 5 votes
@Override
public void rollback() {
    try {
        Connection c = getConnection();
        inTransaction = false;
        c.rollback();
        c.setAutoCommit(true);
    } catch (SQLException sqle) {
        log.warning("\bDatabase rollback failed.  You should probably restart the application.");
    }
}
 
Example 11
Project: the-vigilantes   File: ConnectionRegressionTest.java   View Source Code Vote up 5 votes
/**
 * Tests fix for Bug#75209 - Set useLocalTransactionState may result in partially committed transaction.
 */
public void testBug75209() throws Exception {
    createTable("testBug75209", "(id INT PRIMARY KEY)", "InnoDB");

    boolean useLocTransSt = false;
    do {
        this.stmt.executeUpdate("TRUNCATE TABLE testBug75209");
        this.stmt.executeUpdate("INSERT INTO testBug75209 VALUES (1)");

        final String testCase = String.format("Case: [LocTransSt: %s]", useLocTransSt ? "Y" : "N");

        final Connection testConn = getConnectionWithProps("useLocalTransactionState=" + useLocTransSt);
        testConn.setAutoCommit(false);

        final Statement testStmt = testConn.createStatement();
        try {
            assertEquals(testCase, 1, testStmt.executeUpdate("INSERT INTO testBug75209 VALUES(2)"));

            // This triggers Duplicate-key exception
            testStmt.executeUpdate("INSERT INTO testBug75209 VALUES(2)");
            fail(testCase + ": SQLException expected here!");
        } catch (Exception e) {
            testConn.rollback();
        }
        testStmt.close();

        testConn.setAutoCommit(true);
        testConn.close();

        this.rs = this.stmt.executeQuery("SELECT COUNT(*) FROM testBug75209");
        assertTrue(this.rs.next());
        assertEquals(testCase, 1, this.rs.getInt(1));
    } while (useLocTransSt = !useLocTransSt);
}
 
Example 12
Project: Nird2   File: TransactionIsolationTest.java   View Source Code Vote up 5 votes
@Test
public void testWriteLockTimeoutOnTableWithoutMvcc() throws Exception {
	Connection connection = openConnection(false);
	try {
		createTableAndInsertRow(connection);
	} finally {
		connection.close();
	}
	// Start the first transaction
	Connection txn1 = openConnection(false);
	try {
		txn1.setAutoCommit(false);
		// The first transaction should read the initial value
		assertEquals(123, getCounter(txn1));
		// The first transaction updates the value but doesn't commit yet
		assertEquals(1, setCounter(txn1, 345));
		// Start the second transaction
		Connection txn2 = openConnection(false);
		try {
			txn2.setAutoCommit(false);
			// The second transaction tries to read the value
			try {
				getCounter(txn2);
				fail();
			} catch (SQLException expected) {
				// Expected: the table is locked by the first transaction
			}
			// Abort the transactions
			txn1.rollback();
			txn2.rollback();
		} finally {
			txn2.close();
		}
	} finally {
		txn1.close();
	}
}
 
Example 13
Project: spring-boot-data-source-decorator   File: TracingJdbcEventListenerTests.java   View Source Code Vote up 5 votes
@Test
public void testShouldAddSpanForConnection() throws Exception {
    Connection connection = dataSource.getConnection();
    connection.commit();
    connection.rollback();
    connection.close();

    assertThat(ExceptionUtils.getLastException()).isNull();

    assertThat(spanReporter.getSpans()).hasSize(1);
    Span connectionSpan = spanReporter.getSpans().get(0);
    assertThat(connectionSpan.getName()).isEqualTo("jdbc:/dataSource/connection");
    assertThat(connectionSpan.logs()).extracting("event").contains("commit");
    assertThat(connectionSpan.logs()).extracting("event").contains("rollback");
}
 
Example 14
Project: alfresco-repository   File: ControlDAOImpl.java   View Source Code Vote up 5 votes
/**
 * Calls through to the {@link Connection#setSavepoint(String) current connection}.
 */
@Override
public void rollbackToSavepoint(Savepoint savepoint)
{
    try
    {
        Connection connection = template.getConnection();
        connection.rollback(savepoint);
    }
    catch (SQLException e)
    {
        throw new RuntimeException("Failed to create SAVEPOINT: " + savepoint, e);
    }
}
 
Example 15
Project: UtilsMaven   File: JDBCUtils.java   View Source Code Vote up 5 votes
/**
 * 回滚事务并关闭该连接,该事务连接是线程安全的。
 */
public static void rollbackTransaction() {
    Connection connection = tl_conn.get();
    if (connection == null) {
        throw new RuntimeException("You do not start a Transaction so you can not rollback a transaction!");
    }
    try {
        connection.rollback();
        connection.close();
        tl_conn.remove();
        tl_sp.remove();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Project: spanner-jdbc   File: DMLTester.java   View Source Code Vote up 4 votes
@Override
public void execute(Connection connection) throws SQLException
{
	connection.rollback();
}
 
Example 17
Project: aliyun-maxcompute-data-collectors   File: CatalogQueryManager.java   View Source Code Vote up 4 votes
@Override
public String getPrimaryKey(String tableName) {
  Connection c = null;
  Statement s = null;
  ResultSet rs = null;
  List<String> columns = new ArrayList<String>();
  try {
    c = getConnection();
    s = c.createStatement();

    String primaryKeyQuery = getPrimaryKeyQuery(tableName);
    LOG.debug("Retrieving primary key for table '"
      + tableName + "' with query " + primaryKeyQuery);
    rs = s.executeQuery(primaryKeyQuery);
    while (rs.next()) {
      columns.add(rs.getString(1));
    }
    c.commit();
  } catch (SQLException sqle) {
    try {
      if (c != null) {
        c.rollback();
      }
    } catch (SQLException ce) {
      LoggingUtils.logAll(LOG, "Failed to rollback transaction", ce);
    }
    LoggingUtils.logAll(LOG, "Failed to list primary key", sqle);
    throw new RuntimeException(sqle);
  } finally {
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException re) {
        LoggingUtils.logAll(LOG, "Failed to close resultset", re);
      }
    }
    if (s != null) {
      try {
        s.close();
      } catch (SQLException se) {
        LoggingUtils.logAll(LOG, "Failed to close statement", se);
      }
    }
  }

  if (columns.size() == 0) {
    // Table has no primary key
    return null;
  }

  if (columns.size() > 1) {
    // The primary key is multi-column primary key. Warn the user.
    LOG.warn("The table " + tableName + " "
      + "contains a multi-column primary key. Sqoop will default to "
      + "the column " + columns.get(0) + " only for this job.");
  }

  return columns.get(0);
}
 
Example 18
Project: DBus   File: MySQLManager.java   View Source Code Vote up 4 votes
@Override
public String[] getColumnNames(String tableName) {
    Connection c = null;
    Statement s = null;
    ResultSet rs = null;
    List<String> columns = new ArrayList<String>();
    String schema=tableName.split("\\.")[0];
    tableName=tableName.split("\\.")[1];
    String listColumnsQuery = "SELECT COLUMN_NAME,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS "
          + "WHERE TABLE_SCHEMA = '" + schema + "' "
          + "  AND TABLE_NAME = '" + tableName + "' ";
    
    try {
      c = getConnection();
      s = c.createStatement();
      rs = s.executeQuery(listColumnsQuery);
      while (rs.next()) {
          String columnName=rs.getString(1);
          String columnDataType=rs.getString(2);
          if(SupportedMysqlDataType.isSupported(columnDataType)) {
              columns.add(columnName);
          }
      }
      c.commit();
    } catch (SQLException sqle) {
      try {
        if (c != null) {
          c.rollback();
        }
      } catch (SQLException ce) {
        LOG.warn("Failed to rollback transaction", ce);
      }
      LOG.warn("Failed to list columns from query: "
        + listColumnsQuery, sqle);
      throw new RuntimeException(sqle);
    }catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException re) {
          LOG.warn("Failed to close resultset", re);
        }
      }
      if (s != null) {
        try {
          s.close();
        } catch (SQLException se) {
          LOG.warn("Failed to close statement", se);
        }
      }
    }

    return columns.toArray(new String[columns.size()]);
}
 
Example 19
Project: DBus   File: CatalogQueryManager.java   View Source Code Vote up 4 votes
@Override
public String[] listTables() {
  Connection c = null;
  Statement s = null;
  ResultSet rs = null;
  List<String> tables = new ArrayList<String>();
  try {
    c = getConnection();
    s = c.createStatement();
    rs = s.executeQuery(getListTablesQuery());
    while (rs.next()) {
      tables.add(rs.getString(1));
    }
    c.commit();
  } catch (SQLException sqle) {
    try {
      if (c != null) {
        c.rollback();
      }
    } catch (SQLException ce) {
      LOG.warn("Failed to rollback transaction", ce);
    }
    LOG.warn("Failed to list tables", sqle);
    throw new RuntimeException(sqle);
  }catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
  } finally {
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException re) {
        LOG.warn("Failed to close resultset", re);
      }
    }
    if (s != null) {
      try {
        s.close();
      } catch (SQLException se) {
        LOG.warn("Failed to close statement", se);
      }
    }
  }

  return tables.toArray(new String[tables.size()]);
}
 
Example 20
Project: DBus   File: CatalogQueryManager.java   View Source Code Vote up 4 votes
@Override
public String[] getColumnNames(String tableName) {
  Connection c = null;
  Statement s = null;
  ResultSet rs = null;
  List<String> columns = new ArrayList<String>();
  String listColumnsQuery = getListColumnsQuery(tableName);
  try {
    c = getConnection();
    s = c.createStatement();
    rs = s.executeQuery(listColumnsQuery);
    while (rs.next()) {
      columns.add(rs.getString(1));
    }
    c.commit();
  } catch (SQLException sqle) {
    try {
      if (c != null) {
        c.rollback();
      }
    } catch (SQLException ce) {
      LOG.warn("Failed to rollback transaction", ce);
    }
    LOG.warn("Failed to list columns from query: "
      + listColumnsQuery, sqle);
    throw new RuntimeException(sqle);
  }catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
  } finally {
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException re) {
        LOG.warn("Failed to close resultset", re);
      }
    }
    if (s != null) {
      try {
        s.close();
      } catch (SQLException se) {
        LOG.warn("Failed to close statement", se);
      }
    }
  }

  return columns.toArray(new String[columns.size()]);
}