package cn.itcast.jdbc.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDemo7 {
public static void main(String[] args) {
Connection conn=null;
PreparedStatement pstmt1=null;
PreparedStatement pstmt2=null;
ResultSet rs=null;
//注册驱动 获取数据库连接对象
try {
conn = JDBCUtils.getConnection();
//开启事务
conn.setAutoCommit(false);
//定义sql语句
String sql1="update account set balance=balance-? where id=?";
String sql2="update account set balance=balance+? where id=?";
//获取执行sql对象
pstmt1 = conn.prepareStatement(sql1);
pstmt2 = conn.prepareStatement(sql2);
//给sql语句赋值
pstmt1.setDouble(1,50);
pstmt1.setInt(2,1);
pstmt2.setDouble(1,50);
pstmt2.setInt(2,2);
//增加bug
int a=3/0;
//执行sql语句
pstmt1.executeUpdate();
pstmt2.executeUpdate();
//若程序没问题则提交事务
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
//若程序有问题则回滚事务
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}finally {
JDBCUtils.close(pstmt1,conn);
JDBCUtils.close(pstmt2,null);
}
}
}