JDBC8 - 事物 Dao&Service
事务
JDBC默认每条语句都是进行事务提交
1.关闭自动事务提交
connection.setAutoCommit(false);
2.手动提交或回滚
connection.commit();
connection.rollback();
3.使用try-catch整合1 2
try{
connection.setAutoCommit(false);
connection.commit();
}catch(Exception e){
connection.rollback();
}
将业务结构拆分,Dao(DataBase Access Object)层,封装基础操作
Service层调用基本操作,实现事务的原子化操作
-
事务添加是在业务方法中,注册驱动和获取连接也在业务方法中
-
利用try-catch代码块,开启事务、提交事务、事务回滚
-
将connection传入dao层即可,保证所有dao层的方法使用同一个连接,在同一个事务中
dao层
public class BankDao {
/**
* 加钱的数据库操作方法
* @param account 加钱的账号
* @param money 加钱的金额
*/
public void add(String account,int money, Connection connection) throws Exception {
//3.构建SQL语句
String sql = "update t_bank set money = money + ? where account = ?";
//4.创建statement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//5.占位符赋值
preparedStatement.setObject(1,money);
preparedStatement.setString(2,account);
//6.发生SQL语句,并获取结果
int i = preparedStatement.executeUpdate();
//7.处理结果集
if(i > 0){
System.out.println("加钱成功");
}else {
System.out.println("加钱失败");
}
//8.关闭资源
preparedStatement.close();
}
/**
* 减钱的数据库操作方法
* @param account
* @param money
*/
public void sub(String account,int money, Connection connection) throws Exception {
//3.构建SQL语句
String sql = "update t_bank set money = money - ? where account = ?";
//4.创建statement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//5.占位符赋值
preparedStatement.setObject(1,money);
preparedStatement.setString(2,account);
//6.发生SQL语句,并获取结果
int i = preparedStatement.executeUpdate();
//7.处理结果集
if(i > 0){
System.out.println("减钱成功");
}else {
System.out.println("减钱失败");
}
//8.关闭资源
preparedStatement.close();
}
}
service层
public class BankService {
@Test
public void start() throws Exception {
//zzz -> 500 -> haha
transfer("zzz","haha",500);
}
/**
* TODO:
* 事务添加是在业务方法中
* 利用try-catch代码块,开启事务、提交事务、事务回滚
* 将connection传入dao层即可,保证所有dao层的方法使用同一个连接,在同一个事务中
*
* @param addAccount
* @param subAccount
* @param money
* @throws Exception
*/
public void transfer(String addAccount, String subAccount, int money) throws Exception{
BankDao bankDao = new BankDao();
//一个事务的最基本要求 -- 必须是同一个连接对象 connection
//一个转账方法 属于一个事务 (加钱 减钱)
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql:///atguigu", "root", "123456");
try {
//开启事务 -- 关闭自动提交
connection.setAutoCommit(false);
//执行数据库动作
//将同一个的连接传入不同的方法
bankDao.add(addAccount, money, connection);
System.out.println("-----------");
bankDao.sub(subAccount, money, connection);
//事务提交
connection.commit();
}catch (Exception e){
//事务回滚
connection.rollback();
throw e;
}finally {
connection.close();
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析