20-事务复习
20-事务复习
概述
本文主要复习JDBC中的事务
事务就是一组数据的修改操作要么一起成功,要么一起失败
重点
需要开启事务
事务执行成功需手动提交
事务执行失败需要回滚
实践
package com.kuang.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 功能描述
*
* @since 2022-09-02
*/
public class TransactionDemo {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// useUnicode=true&CharactorEncoding=utf-8
String url = "jdbc:mysql://xxxx3306/xxx";
String user = "xxx";
String password = "xxx";
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
// 连接数据库
connection = DriverManager.getConnection(url, user, password);
// 开启事务
connection.setAutoCommit(false);
// 向数据库发送sql的对象 Statement
String sql = "update account set money=money-100 where name='张三'";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
// // 制造异常
// int a = 100/0;
String sql1 = "update account set money=money+100 where name='李四'";
preparedStatement = connection.prepareStatement(sql1);
preparedStatement.executeUpdate();
connection.commit();
System.out.println("转账成功");
} catch (Exception e){
System.out.println("转账失败");
// 操作失败就回滚
connection.rollback();
} finally {
// 关闭资源(一定要做),先开后关
preparedStatement.close();
connection.close();
}
}
}