使用DBUtils完成事务处理功能
来源:互联网 发布:python有蚁群算法包吗 编辑:程序博客网 时间:2024/06/05 20:48
注意:
DBUtils进行事务处理的原理,是在Service层获得连接,以保证事务处理过程中的Connection对象为同一个Connection。
Service层代码:
/** * 事务管理方式:向下传递Connection。有侵入性。使用DBUtils * 业务层事务管理转账的方法 * @param from * @param to * @param money */ public void transfer(String from, String to, double money) { //调用dao层 AccountDao accountDao = new AccountDao(); //方法一:因为必须保证连接为同一个连接,所以在业务层获得连接,再将连接传递到持久层,代码具有侵入性。 //DBUtils使用的方法 Connection conn = null; try { //获得连接 conn = C3P0Utils.getConnection(); //设置事务不自动提交 conn.setAutoCommit(false); //调用持久层 accountDao.outMoney(conn,from,money); //如果有异常 //int a = 1 / 0 ; accountDao.inMoney(conn,to,money); //提交事务,并安静的关闭连接 DbUtils.commitAndCloseQuietly(conn); } catch (SQLException e) { //有异常出现时,回滚事务,并安静的关闭连接 DbUtils.rollbackAndCloseQuietly(conn); e.printStackTrace(); } }
Dao层 代码:
public void outMoney(Connection conn, String from, double money) { QueryRunner qr = new QueryRunner(); try { String sql = "update account set money = money - ? where username = ?"; qr.update(conn, sql, money,from); } catch (SQLException e) { e.printStackTrace(); } } public void inMoney(Connection conn, String to, double money) { QueryRunner qr = new QueryRunner(); try { String sql = "update account set money = money + ? where username = ?"; qr.update(conn, sql, money,to); } catch (SQLException e) { e.printStackTrace(); } }
阅读全文
0 0
- 使用DBUtils完成事务处理功能
- 使用dbutils完成curd操作
- dbutils 的使用,事务处理,操作多表
- Apache-dbutils 简介及事务处理
- 使用PLSQL完成功能
- DbUtils使用
- DBUtils使用
- DBUtils使用
- DBUtils使用
- Dbutils使用
- 使用dbutils
- 使用DBUtils为MySQL实现连接池功能
- 使用事务处理
- (五)JDBC连接池&DBUtils—DBUtils完成CRUD
- 使用HTML_QuickForm快速完成自动表单完成功能
- MASM32编程使用自动完成功能
- 使用SQL完成hibernate saveOrUpdate功能
- 使用AutoComplete Extender实现自动完成功能
- 解读前端开发工程师必备技能
- Tomcat的热部署(以后就不用重起了)
- Linux命令学习笔记(一)
- android内存分析命令
- 西瓜书《机器学习》课后答案——Chapter2
- 使用DBUtils完成事务处理功能
- datagrid 删除选中的行
- 第二章:jsp内置对象的使用
- Mongo数据库搭建和基本使用
- EasyRecyclerView的基本使用
- Android开发工具
- 如何把已经提交的commit, 从一个分支放到另一个分支
- JavaScript、ES5和ES6的介绍和区别
- 爬取网易云音乐下面的热门评论