JDBC Basics |
There are times when you do not want one statement to take effect unless another one also succeeds. For example, when the proprietor of The Coffee Break updates the amount of coffee sold each week, he will also want to update the total amount sold to date. However, he will not want to update one without also updating the other; otherwise, the data will be inconsistent. The way to be sure that either both actions occur or neither action occurs is to use a transaction. A transaction is a set of one or more statements that are executed together as a unit, so either all of the statements are executed, or none of the statements is executed.Disabling Auto-commit Mode
When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. (To be more precise, the default is for an SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)
The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode. This is demonstrated in the following line of code, where
con
is an active connection:con.setAutoCommit(false);Committing a Transaction
Once auto-commit mode is disabled, no SQL statements will be committed until you call the method
commit
explicitly. All statements executed after the previous call to the methodcommit
will be included in the current transaction and will be committed together as a unit. The following code, in whichcon
is an active connection, illustrates a transaction:con.setAutoCommit(false); PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 50); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(); PreparedStatement updateTotal = con.prepareStatement( "UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); con.commit(); con.setAutoCommit(true);In this example, auto-commit mode is disabled for the connection
con
, which means that the two prepared statementsupdateSales
andupdateTotal
will be committed together when the methodcommit
is called. Whenever thecommit
method is called (either automatically when auto-commit mode is enabled or explicitly when it is disabled), all changes resulting from statements in the transaction will be made permanent. In this case, that means that theSALES
andTOTAL
columns for Colombian coffee have been changed to50
(ifTOTAL
had been0
previously) and will retain this value until they are changed with another update statement. Sample Code in the Code Appendix **link to APP** illustrates a similar kind of transaction but uses afor
loop to supply values to thesetXXX
methods forupdateSales
andupdateTotal
.The final line of the previous example enables auto-commit mode, which means that each statement will once again be committed automatically when it is completed. You will then be back to the default state where you do not have to call the method
commit
yourself. It is advisable to disable auto-commit mode only while you want to be in transaction mode. This way, you avoid holding database locks for multiple statements, which increases the likelihood of conflicts with other users.Using Transactions to Preserve Data Integrity
In addition to grouping statements together for execution as a unit, transactions can help to preserve the integrity of the data in a table. For instance, suppose that an employee was supposed to enter new coffee prices in the table
COFFEES
but delayed doing it for a few days. In the meantime, prices rose, and today the owner is in the process of entering the higher prices. The employee finally gets around to entering the now outdated prices at the same time that the owner is trying to update the table. After inserting the outdated prices, the employee realizes that they are no longer valid and calls theConnection
methodrollback
to undo their effects. (The methodrollback
aborts a transaction and restores values to what they were before the attempted update.) At the same time, the owner is executing aSELECT
statement and printing out the new prices. In this situation, it is possible that the owner will print a price that was later rolled back to its previous value, making the printed price incorrect.This kind of situation can be avoided by using transactions. If a DBMS supports transactions, and almost all of them do, it will provide some level of protection against conflicts that can arise when two users access data at the same time.
To avoid conflicts during a transaction, a DBMS will use locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. (Note that in auto-commit mode, where each statement is a transaction, locks are held for only one statement.) Once a lock is set, it will remain in force until the transaction is committed or rolled back. For example, a DBMS could lock a row of a table until updates to it have been committed. The effect of this lock would be to prevent a user from getting a dirty read, that is, reading a value before it is made permanent. (Accessing an updated value that has not been committed is considered a dirty read because it is possible for that value to be rolled back to its previous value. If you read a value that is later rolled back, you will have read an invalid value.)
How locks are set is determined by what is called a transaction isolation level, which can range from not supporting transactions at all to supporting transactions that enforce very strict access rules.
One example of a transaction isolation level is
TRANSACTION_READ_COMMITTED
, which will not allow a value to be accessed until after it has been committed. In other words, if the transaction isolation level is set toTRANSACTION_READ_COMMITTED
, the DBMS will not allow dirty reads to occur. The interfaceConnection
includes five values which represent the transaction isolation levels you can use in JDBC.Normally, you do not need to do anything about the transaction isolation level; you can just use the default one for your DBMS. JDBC allows you to find out what transaction isolation level your DBMS is set to (using the
Connection
methodgetTransactionIsolation
) and also allows you to set it to another level (using theConnection
methodsetTransactionIsolation
). Keep in mind, however, that even though JDBC allows you to set a transaction isolation level, doing so will have no effect unless the driver and DBMS you are using support it.When to Call the Method rollback
As mentioned earlier, calling the method
rollback
aborts a transaction and returns any values that were modified to their previous values. If you are trying to execute one or more statements in a transaction and get anSQLException
, you should call the methodrollback
to abort the transaction and start the transaction all over again. That is the only way to be sure of what has been committed and what has not been committed. Catching anSQLException
tells you that something is wrong, but it does not tell you what was or was not committed. Since you cannot count on the fact that nothing was committed, calling the methodrollback
is the only way to be sure.Sample Code in the Code Appendix **link to APP** demonstrates a transaction and includes a
catch
block that invokes the methodrollback
. In this particular situation, it is not really necessary to callrollback
, and we do it mainly to illustrate how it is done. If the application continued and used the results of the transaction, however, it would be necessary to include a call torollback
in thecatch
block in order to protect against using possibly incorrect data.
JDBC Basics