Java Tutorial - Java Script :
Transactions
Most databases need to support transactions. Transactions ensure data integrity during complex database changes. An easy example to consider is moving money from one bank account to another, as illustrated in Figure 8.2. Say for example, that there is $100 in your savings account and you want to move $50 into your checking account. This requires two separate operations, removing $50 from savings and then depositing it into checking. When the operations are complete, you should have $50 less in savings and $50 more in checking. If either operation fails, the system is wrong and out of balance. For example, if the removal of the $50 from savings succeeds but adding it to checking fails, you’re short $50. If the removal fails instead, but you still add $50 to checking, the bank is out $50.
(Although you might not mind that, the bank would certainly be unhappy). In short, in order to keep everyone happy and to keep the system in a balanced, or consistent, state, both actions must succeed or both must fail. This is the basic requirement for a transaction. Transactions enforce four rules, known as the ACID properties, for each letter of the acronym:
A. Atomic property ensures that actions all succeed or fail as a group within a transaction.
C. Consistent property states that the system will be in a consistent state both before the transaction begins and after it is completed.
I. Isolated property ensures that one transaction does not affect other transactions as they are occurring.
D. Durable property ensures that once a transaction has been completed it is permanent.
In some dialects of SQL, transactions can be marked with a BEGIN TRANSACTION statement prior to the statements that will be incorporated within the transaction. At the end of the transaction a COMMIT keyword is used to complete the transaction. If the transaction cannot be completed, the ROLLBACK keyword is used to reverse the actions that make up the transaction. The java.sql.Connection interface provides several methods for handling transactions. We will briefly examine four of these:
java.sql.connection.setAutoCommit( boolean )
java.sql.connection.getAutoCommit( boolean )
Savings Checking System
Total
Actions
$100
– 50
$50
$50
+ 50
$100
$150
$150
$50
$
$
java.sql.connection.commit()
java.sql.connection.rollback()
The get and set AutoCommit methods determine the transactional behavior of each statement submitted to the database. With AutoCommit set to true, (the default) each statement is included in its own transaction. With AutoCommit set to false, each statement is included in a single transaction until either the commit() method is invoked completing the transaction (and starting the next one) or the rollback() method is invoked, aborting the
transaction.
