Using Transactions in JDBC

By: Ramlak Printer Friendly Format    

By default, JDBC classes operate in auto-commit mode. This means that each SQL statement executed is considered a separate transaction ( a singleton transaction) and a commit is made at the completion of the statement. In order to group a set of transactions together, this autocommit mode must be disabled using the connection class setAutoCommit method and passing the method boolean false value.

With autocommit disabled, there is always an implicit transaction in place. To commit a series of previously executed SQL statements to the database, an explicit commit can be made by calling the Connection method commit. Alternatively, a rollback can be made by calling the Connection method rollback. This rolls back the current transaction and restores the database to the state bit was in before the start of the current transaction. Failure to commit a transaction before closing the corresponding Connection object will lead to an automatic rollback of the database updates; all work will be lost. Developers should be sure that all work is committed to the database before closing the Connection.

Various database-dependant isolation levels can be set. There are methods in the DatabaseMetaData class to learn the existing defaults in place in the current session and methods in the Connection class to change the current isolation level.

JDBC Isolation Mode Description
TRANSACTION_NONE Transactions are not supported. Not all databases support this mode; most require some level of transactions to be in place.
TRANSACTION_READ_COMMITTED Only reads on the current row are repeatable.
TRANSACTION_READ_UNCOMMITTED Rows being used by a tranaction can be read even if the rows have not been committed.
TRANSACTION_REPEATABLE_READ Reads on all rows of a result are repeatable.
TRANSACTION_SERIALIZABLE Reads on all rows of a transaction are repeatable in the order in which they were executed.


Ask a Question



Most Viewed Articles (in JDBC )

Latest Articles (in JDBC)

Comment on this tutorial