Using Transactions in JDBC
By: Ramlak in JDBC Tutorials on 2007-04-06
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. |
Here's a sample program that demonstrates how to use transactions in JDBC:
import java.sql.*; public class TransactionExample { public static void main(String[] args) { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password"); conn.setAutoCommit(false); // disable auto-commit // Perform some operations Statement stmt = conn.createStatement(); stmt.executeUpdate("INSERT INTO orders (customer_id, order_date, amount) VALUES (1, '2022-05-01', 100.00)"); stmt.executeUpdate("UPDATE customers SET balance = balance - 100.00 WHERE customer_id = 1"); // Commit the transaction conn.commit(); System.out.println("Transaction committed successfully."); } catch (SQLException ex) { // Rollback the transaction if there's an exception if (conn != null) { try { conn.rollback(); } catch (SQLException ex2) { ex2.printStackTrace(); } } ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } finally { // Close the connection if (conn != null) { try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } }
In this program, we first disable the auto-commit mode using the setAutoCommit(false)
method on the Connection
object. This means that all changes to the database will be treated as part of a transaction until we explicitly commit the transaction.
We then perform some operations, including an INSERT
and an UPDATE
statement, which are both part of the same transaction. If any exception occurs, we catch it and rollback the transaction using the rollback()
method on the Connection
object.
If there are no exceptions, we commit the transaction using the commit()
method on the Connection
object.
Finally, we close the connection in the finally
block.
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Data Access Technologies in Java
JDBC and Tomcat context settings
TEXT datatype SPLIT in MSSQL - to solve the 8000 limit set by varchar
What is Referential Integrity in databases?
Handling CSV in Stored Procedures
java.lang.NoClassDefFoundError and java.lang.NoSuchMethodError
Calling a Stored Procedure from JDBC in Java
setSavepoint and releaseSavepoint Example in Java
Result Sets, Cursors and Transactions in SQL
Stored Procedures example in SQL
Using the DriverManager Class vs Using a DataSource Object for a connection
Comments