4/09/2012

How to make a transaction in SQL?

When we deal with e-commerce or other business, how to make a transaction?
During the process, there may be multiple queries. How the database handle interrupt errors?
We know that the transaction should be 'atomic'. Change should only effect after all the queries are successfully executed. Any interrupt should cause the database roll back to the initial status before making the transaction.

Most easy way:

01 /**
02 * test how to make transactions in query.
03 * conn.setAutoCommit(false);
04 *      ...
05 *      SQLs
06 *      ...
07 * conn.commit();     
08 */
09 package com.company.tests;
10 
11 import java.sql.Connection;
12 import java.sql.ResultSet;
13 import java.sql.Statement;
14 import com.company.utils.JDBCUtil;
15 
16 public class OracleTest4 {
17 
18     public static void main(String[] args){
19         try{
20             
21             Connection conn = JDBCUtil.getConnection();
22             conn.setAutoCommit(false); // default : true
23             String sql = "insert into Sample Values('Bobs',71)";
24             Statement st= conn.createStatement();
25             st.executeUpdate(sql); 
26             sql = "select * from Sample";
27             ResultSet rs = st.executeQuery(sql);
28             while(rs.next()){
29                 System.out.println(rs.getString("Name") + "\t" + rs.getInt("Age"));
30                 
31             }
32             conn.commit();
33             rs.close();
34         }catch(Exception e){
35             e.printStackTrace();
36         }
37     }
38 
39 }
We can see from the code, there is a block:
conn.setAutoCommit(false);
...
SQLs
...
conn.commit(); 
The change will effect only after all the SQLs are successfully executed.
If any SQL in the block has exceptions or errors, the database will not be updated.

PS: JDBCUtil.getConnection() please refer to my last post:
http://bosbluebluesky.blogspot.com/2012/04/jdbc-configuration-and-implementation.html

No comments:

Post a Comment