為了保證數(shù)據(jù)的一致性、完整性
比如100條數(shù)據(jù)颁督,插入數(shù)據(jù)庫
前50條成功插入渣触,后面50沒有成功插入,這就屬于不完整數(shù)據(jù)
所以我們要用事務(wù)管理來解決
// 設(shè)置為false蟋字,就不會(huì)自動(dòng)提交到數(shù)據(jù)庫稿蹲,比如前50條數(shù)據(jù)通過,后面50不通過鹊奖,這樣也不會(huì)進(jìn)入數(shù)據(jù)庫
conn.setAutoCommit(false);
但是苛聘,使用conn.setAutoCommit(false);要注意數(shù)據(jù)庫死鎖
所以
(設(shè)定setAutoCommit(false)沒有在catch中進(jìn)行Connection的rollBack操作,操作的表就會(huì)被鎖住忠聚,造成數(shù)據(jù)庫死鎖):
try {
conn = getConnection();
conn.setAutoCommit(false);
insertUserData(conn);
insertAddressData(conn);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("=====捕獲到sql異常======");
e.printStackTrace();
try {
conn.rollback();
System.out.println("======事務(wù)回滾成功=====");
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
注意:
setAutoCommit在try里面
conn.rollback();一定要在catch里面
// conn.rollback();是數(shù)據(jù)回滾设哗,是數(shù)據(jù)庫中事物的執(zhí)行,有一條插入失敗两蟀,所有的都不插入熬拒,數(shù)據(jù)庫回滾到操作之前的樣子
代碼
package com.chenzebin.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TransactionTest {
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return conn;
}
public static void insertUserData(Connection conn) throws SQLException {
String sql = "insert into tbl_user(id,name,password,email)" + "values(10,'Tom','123456','tom@gmail.com')";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向用戶表插入" + count + "條記錄");
}
public static void insertAddressData(Connection conn) throws SQLException {
String sql = "insert into tbl_address(id,city,country,user_id)" + "values(1,'shanghai','china','10')";
Statement st = conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向地址表中插入了" + count + "條記錄");
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
insertUserData(conn);
insertAddressData(conn);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("=====捕獲到sql異常======");
e.printStackTrace();
try {
conn.rollback();
System.out.println("======事務(wù)回滾成功=====");
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}finally {
try {
if(conn != null) {
conn.close();
}
} catch (Exception e3) {
// TODO: handle exception
e3.printStackTrace();
}
}
}
}