When Jdbc program to the database when obtaining a Connection object, the Connection object is automatically submit SQL statement on it sent to the database by default. To turn off this default submission, which allows multiple SQL execution in a transaction and to ensure that these statements is at the same time implemented jointly, for this we should define a multi-statement transactions.
Among them, bank transfer this case, that best describes the importance of the transaction to use.
update from account set money=money-100where name=‘a’;
update from account set money=money+100 wherename=‘b’;
Because this time, the increase or decrease in two accounts together is performed. This is similar to real-life examples of synchronous communication there are many, here, not repeat them.
Of course, for the preparation of the transaction, but also to follow a certain order:
First, set the affairs of non-automatic submission submission:
conn.setAutoCommit(false);
Next, would need to add code into a transaction try, catch block.
Then, Adding a transaction commit operation within the try block, showing no abnormal operation, commit the transaction.
conn.commit();
In particular, do not forget to add in the catch block rolls back the transaction, it represents an abnormal operation occurs, cancel the transaction:
conn.rollback();
Finally, a way to automatically submit the transaction commits:
conn.setAutoCommit(true);
In this way, through a few simple steps, we will be able to complete the preparation of the transaction.
Example: The method defines a transaction and to achieve consistency between statements in the operation method
Connection con =null;
Statement st=null;
ResultSet rs=null;
PreparedStatement ps=null;
publicvoid startTransaction(){
. CON = DBCManager getConnect (); // Get the connection object
try {
// Set the transaction is non-automatic submission submission:
con.setAutoCommit(false);
// you will need to add code together into the affairs of try, catch block
// Create the statement is executed
String sql ="delete from me where id = 7";
String sql1 = "update me set name ='chengong' ,age ='34' where id =4";
// Run the transaction
ps = con.prepareStatement(sql);
ps.executeUpdate();
ps = con.prepareStatement (sql1);
ps.executeUpdate();
// add transaction submitted within the try block of the operation, showing no abnormal operation, to commit the transaction.
con.commit ();
} catch (SQLException e) {
try {
// add transaction rollback in the catch block, indicates an abnormal operation occurs, undo transaction:
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generatedcatch block
e1.printStackTrace ();
}
e.printStackTrace ();
}finally{
try {
// Set the transaction presented in a way to automatically submit:
con.setAutoCommit(true);
} catch (SQLException e) {
// TODO Auto-generatedcatch block
e.printStackTrace ();
}
DBCManager.release(rs, ps, con);
}
}