事務的概念最開始出現(xiàn)在關系型數(shù)據(jù)庫中袱讹,英文解釋如下:
A database transaction is a larger unit that frames multiple SQL statements. A transaction ensures that the action of the framed statements is atomic with respect to recovery.
事務是確保"同時成功則成功席镀,任何一個失敗則失敗"的一種機制厢呵。一個事務往往包括三種動作行為:開始事務(Begin Transaction)华蜒,提交事務(Commit)和回滾(Rollback)迹恐。從開始事務到提交事務過程中所發(fā)生的一切數(shù)據(jù)庫修改要么同時成功(被Commit批什,固化在數(shù)據(jù)庫中),要么一個失敗链烈,大家同時回復原有狀態(tài)(Rollback厉斟,數(shù)據(jù)庫回復到事務開始時的狀態(tài))。
簡單的理解:它是一個操作序列强衡,這些操作要么都執(zhí)行擦秽,要么都不執(zhí)行,它是一個不可分割的工作單位漩勤。
事務基本屬性:
事務的ACID特點分別是指原子性(atomicity)感挥、一致性(consistency)、隔離性(isolation)和持久性(durability)越败。
原子性(atomicity) :一個事務是一個不可分割的工作單位链快,事務中包括的諸操作要么都做,要么都不做眉尸。
一致性(consistency):事務必須是使數(shù)據(jù)庫從一個一致性狀態(tài)變到另一個一致性狀態(tài)域蜗。一致性與原子性是密切相關的。
隔離性(isolation) :一個事務的執(zhí)行不能被其他事務干擾噪猾。即一個事務內(nèi)部的操作及使用的數(shù)據(jù)對并發(fā)的其他事務是隔離的霉祸,并發(fā)執(zhí)行的各個事務之間不能互相干擾。
持久性(durability) :持續(xù)性也稱永久性(permanence)袱蜡,指一個事務一旦提交丝蹭,它對數(shù)據(jù)庫中數(shù)據(jù)的改變就應該是永久性的。接下來的其他操作或故障不應該對其有任何影響坪蚁。
import java.sql.*;
/**
* 測試事務的基本用法
* @author Administrator
*
*/
public class TestCommit {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","123456");
//JDBC中默認為自動提交,此處設為手動提交
conn.setAutoCommit(false);
ps = conn.prepareStatement("insert into user (name,age) values (?,?)");
ps.setObject(1, "王五");
ps.setObject(2, "13");
ps.executeUpdate();
System.out.println("ps插入的用戶");
//此處SQL語句錯誤,拋出異常,執(zhí)行回滾操作
ps = null;
ps = conn.prepareStatement("insert into user (name,pwd) values (?,?,?)");
ps.setObject(1, "李四");
ps.setObject(2, "123456");
ps.executeUpdate();
System.out.println("ps1插入的用戶");
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}