问题描述
JDBC中如何添加事务
解决方案:
public static void main(String[] args) throws Exception {
//1.0注册驱动
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://01.01.01.01:3306/demo01";
String userName="demo01";
String passWord="123456";
Connection conn= DriverManager.getConnection(url,userName,passWord);
//定义sql
String sql ="update tb_account set money=money+500 where `Name`='张三'";
Statement stmt=conn.createStatement();
try{
//开启事务 false:手动提交 true:自动提交
conn.setAutoCommit(false);
//执行sql 获取影响行数
int count =stmt.executeUpdate(sql);
//把结果打印
System.out.println(count);
} catch(Exception throwables){
//回滚事务
conn.rollback();
throwables.printStackTrace();
}
//释放资源
stmt.close();;
conn.close();