package cn.itcast.jdbc.cn.itcast.jdbc;
import cn.itcast.util.JDBCutil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author KuKaFei.Hai
* @date 2020/5/9 : 15:50
*/
public class TransferAccounts {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmtFrom = null;
PreparedStatement pstmtTo = null;
try {
conn = JDBCutil.getConnection();
//开启事务
conn.setAutoCommit(false);
String sqlFrom = "update count set count = count - ? where id = ?";
String sqlTo = "update count set count = count + ? where id = ?";
pstmtFrom = conn.prepareStatement(sqlFrom);
pstmtTo = conn.prepareStatement(sqlTo);
pstmtFrom.setInt(1, 500);
pstmtFrom.setInt(2, 1);
pstmtTo.setInt(1, 500);
pstmtTo.setInt(2, 2);
int from = pstmtFrom.executeUpdate();
System.out.println(from);
int to = pstmtTo.executeUpdate();
System.out.println(to);
//提交事务,如果程序执行到这里,说明数据操作完毕
//int c = 3 / 0; 人为异常
conn.commit();
System.out.println("转账成功,影响:" + (from + to) + "行数据");
} catch (Exception e) { //SQLException e 抓大异常,只有报错就要回滚
//一但执行的语句有问题,就执行这里的回滚事务
try {
if (conn != null) { //判断下,是否有空指针,回滚事务
conn.rollback();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
} finally {
JDBCutil.closeAll(pstmtFrom, null);
JDBCutil.closeAll(pstmtTo, conn);
}
}
}