import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import JDBC.SqlHelper;
public class TransactionDemo {
/*
* 事务四大特性:原子性:事务的执行要么都成功,要么都失败,回滚。
* 一致性:事务的处理要保持一致性
* 隔离性:事务要排队
* 持久性:事务一旦提交,必须完成。
*/
public static void main(String[] args) {
CheckAccount();
String payId = "3";
String reId = "2";
int money = 10000;
pay(payId, reId, money);
System.out.println("-------------------------------");
CheckAccount();
}
public static void pay(String payId, String reId, int money) {
Connection conn = null;
try {
conn = SqlHelper.getConnection();
conn.setAutoCommit(false); // 取消自动提交
// 先判断账户余额是否足够, 不够则抛出异常
String searchSql = "SELECT salary FROM jdbc_table_3 WHERE id = ?";
PreparedStatement ps = conn.prepareStatement(searchSql);
ps.setString(1, payId);
ResultSet rs = ps.executeQuery();
rs.next();
if(money > rs.getInt("salary")) {
throw new Exception("账户余额不足!");
}
rs.close();
ps.close();
// 进行转账操作
String paySql = "UPDATE jdbc_table_3 "
+ "SET salary = salary + ? "
+ "WHERE id = ?";
PreparedStatement ps1 = conn.prepareStatement(paySql);
ps1.setInt(1, -money);
ps1.setString(2, payId);
int n = ps1.executeUpdate();
if(n != 1) {
throw new Exception("账号可能不唯一!");
}
ps1.setInt(1, money);
ps1.setString(2, reId);
int n1 = ps1.executeUpdate();
if(n1 != 1) {
throw new Exception("账号可能不唯一!");
}
ps1.close();
conn.commit(); // 事务的提交
}catch(Exception e) {
e.printStackTrace();
SqlHelper.rollback(conn);
}finally {
SqlHelper.close(conn);
}
}
public static void CheckAccount() {
Connection conn = null;
try {
conn = SqlHelper.getConnection();
String Sql = "SELECT * FROM jdbc_table_3";
PreparedStatement ps = conn.prepareStatement(Sql);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
System.out.println("id:" + rs.getString("id") + " name:" + rs.getString("name") + " salary:" + rs.getInt("salary"));
}
}catch(Exception e) {
e.printStackTrace();
}finally {
SqlHelper.close(conn);
}
}
}