1.事務:將多條SQL語句綁定在一塊兒要麼都成功,要麼都不成功java
2.應用:轉帳mysql
3.代碼sql
package cn.ma.transitionmanager.jdbc;數據庫
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.UUID;dom
import org.junit.Test;ui
public class TransitionManager {
@Test//想數據庫插入數據
public void testInsertDataTransitionManager() throws Exception{
Connection conn=null; //鏈接
Statement stmt=null; //
try {
//1.加載驅動
Class.forName("com.mysql.jdbc.Driver");
//2.得到鏈接
conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/day20", "root", "root");
//3.得到執行對象
stmt = conn.createStatement();
//4.執行SQL
UUID uuid = UUID.randomUUID();
Date d = new Date();
String time = d.toLocaleString().toString();
String sql="insert into t_transitionManager values('"+uuid+"','張三','1000','666','"+time+"')";
stmt.executeUpdate(sql);
UUID uuid2 = UUID.randomUUID();
String time2 = d.toLocaleString().toString();
String sql2="insert into t_transitionManager values('"+uuid2+"','李四','1000','999','"+time+"')";
stmt.executeUpdate(sql2);spa
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
//6.關閉資源
stmt.close();
conn.close();
}
}
@Test//更新數據庫數據
public void testupdateDataTransitionManager() throws Exception{
Connection conn=null; //鏈接
Statement stmt=null; //
try {
//1.加載驅動
Class.forName("com.mysql.jdbc.Driver");
//2.得到鏈接
conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/day20", "root", "root");
//3.得到執行對象
stmt = conn.createStatement();
//4.執行SQL
conn.setAutoCommit(false);//開啓事務。手動提交事務
String sql="update t_transitionManager set money=money-100 where accountnumber='999'";
String sql2="update t_transitionManager set money=money+100 where accountnumber='666'";
stmt.executeUpdate(sql);
int i =10/0;//異常代碼
stmt.executeUpdate(sql2);
conn.commit();//提交事務
} catch (ClassNotFoundException e) {
e.printStackTrace();
conn.rollback();//回滾事務
}finally {
//6.關閉資源
//關閉資源
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}對象
4.表結構事務
5.注意點資源
開始事務必須在SQL執行以前