DataBase transaction February 14, 2008
Posted by essamabdelaziz in DataBase.trackback
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.
Using Transactions
There are times when you do not want one statement to take effect unless another one completes. 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 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.
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 is 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:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author javadb.com
*/
public class Main {
/**
* Updates tables using a transaction
*/
public void updateDatabaseWithTransaction() {
Connection connection = null;
Statement statement = null;
try {
Class.forName(“[nameOfDriver]“);
connection = DriverManager.getConnection(“[databaseURL]“,
“[userid]“,
“[password]“);
//Here we set auto commit to false so no changes will take
//effect immediately.
connection.setAutoCommit(false);
statement = connection.createStatement();
//Execute the queries
statement.executeUpdate(“UPDATE Table1 SET Value = 1 WHERE Name = ‘foo’”);
statement.executeUpdate(“UPDATE Table2 SET Value = 2 WHERE Name = ‘bar’”);
//No changes has been made in the database yet, so now we will commit
//the changes.
connection.commit();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
try {
//An error occured so we rollback the changes.
connection.rollback();
} catch (SQLException ex1) {
ex1.printStackTrace();
}
} finally {
try {
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().updateDatabaseWithTransaction();
}
}
Comments»
No comments yet — be the first.