工具类如上篇 https://blog.csdn.net/Shelysure/article/details/109129476
下面代码块中,我们手动制造了异常
因为开启了事务,在出现异常后进行了回滚事务
所以数据库里的内容不会变化
public class JdbcDemo10 {
public static void main(String[] args) {
Connection conn=null;
PreparedStatement pstmt1=null;
PreparedStatement pstmt2=null;
try {
//1.获取连接
conn = JDBCUtils.getConnection();
//开启事务
conn.setAutoCommit(false);
//2.定义sql
//2.1 张三-500
String sql1="update account set balance = balance - ? where id = ?";
//2.2 李四+500
String sql2="update account set balance = balance + ? where id = ?";
//3.获取执行sql对象
pstmt1 = conn.prepareStatement(sql1);
pstmt2 = conn.prepareStatement(sql2);
//4.设置参数
pstmt1.setDouble(1,500);
pstmt1.setDouble(2,1);
pstmt2.setDouble(1,500);
pstmt2.setDouble(2,2);
//5.执行sql
pstmt1.executeUpdate();
pstmt2.executeUpdate();
//手动制造异常
int i=3/0;
pstmt2.executeUpdate();
//提交事务
conn.commit();
} catch (Exception e) {
//事务回滚
try {
if (conn!=null)//如果conn不为null才进行回滚
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
JDBCUtils.close(pstmt1,conn);
JDBCUtils.close(pstmt2,null);
}
}
}
执行代码
刷新表后,数据是没有改变的