Transactions
Autocommit
By default JDBC connections start in auto-commit mode. Each individual SQL statement is executed within its own transaction that is committed when the statement completes.
Explicit transactions can be used by disabling auto-commit with the connection's setAutoCommit method. In this mode a SQL statement starts an implicit transaction that runs until the transaction is committed or rolled back. After the commit or rollback another transaction is automatically created.
Only one transaction can be active on the connection at the same time. That
transaction is applied to all statements run on the connection no matter what
Statement object they are executed from.
Connection conn; Statement stmt = conn.createStatement(); // This creates a new transaction for the next group of SQL statements. conn.setAutoCommit(false); // Both of these statements execute in the same transaction stmt.execute("INSERT INTO ExampleTable(ExampleCol) VALUES ('ExampleVal1')"); stmt.execute("INSERT INTO ExampleTable(ExampleCol) VALUES ('ExampleVal2')"); // This ends the current transaction and begins a new one for the next group of statements conn.commit();
Committing and Rolling Back Transactions
Once auto-commit has been disabled, the active transaction may be committed
using the connection's commit method. Committing accepts all the changes in the
transaction and persists them if they are consistent:
conn.commit();The active transaction may be rolled back using the connection's rollback method. Rolling back undoes all changes performed in the transaction:
conn.rollback();