代码实现事务
package cn.dj.www.lesson02;
import cn.dj.www.lesson01.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
conn = JdbcUtil.getConnection();
//关闭数据库自动提交,自动会开启事务
conn.setAutoCommit(false);
String sql1 = "update account set money = money -100 where name = 'A'";
pst = conn.prepareStatement(sql1);
pst.executeUpdate();
int x=1/0;//测试失败的情况
String sql2 = "update account set money = money +100 where name = 'B'";
pst = conn.prepareStatement(sql2);
pst.executeUpdate();
System.out.println("成功");
conn.commit();
} catch (SQLException e) {
// 如果失败默认回滚
// try {
// conn.rollback();//失败回滚事务
// } catch (SQLException e1) {
// e1.printStackTrace();
// }
e.printStackTrace();
}finally {
JdbcUtil.release(conn,pst,rs);
}
}
}