QueryRunner 事务,转账

1 ,建表 :	
	
	create table account(
		id int auto_increment primary key,
		name varchar(32),
		morney long
	);
	
	数据 :
	
	1	龙	1000
	2	恺	1000
	
2 ,配置数据源 :	
	
	c3p0-config.xml
	
3 ,工具类,C3p0Util :这个讲究的啦  	
	
	要保证线程安全
	
	用到他 :
	
		private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	
	tl.get();
	tl.set();
	tl.remove();
	
4 ,dao :转入,转出	
	
	public class CountDao {
		public void in(int id,long morney) throws SQLException {
			String sql = "update acount set morney=morney+? where id=?";
			QueryRunner qr = new QueryRunner();
			qr.update(C3p0Util.getConn(), sql, morney,id);
		}
		public void out(int id,long morney) throws SQLException {
			String sql = "update acount set morney=morney-? where id=?";
			QueryRunner qr = new QueryRunner();
			qr.update(C3p0Util.getConn(), sql, morney,id);
		}
	}
	
5 ,service 转账	
	
	public void transMorney(int out,int in,long morney) {
		CountDao dao = new CountDao();
		Connection conn = null;
		try {
			conn = C3p0Util.getConn();
			//	开启事务
			conn.setAutoCommit(false);
			dao.in(in, morney);
			//	制造异常 -----------------------------------如果出现异常就全部回滚
			int i=1/0;
			dao.out(out, morney);
			//	提交事务
			DbUtils.commitAndCloseQuietly(conn);
		} catch (SQLException e) {
			//	回滚事务
			DbUtils.rollbackAndCloseQuietly(conn);
			e.printStackTrace();
		} finally {
			//	释放资源
			C3p0Util.remove();
		}
	}
	
6 ,测试 :	
	
	public static void main(String[] args) {
		CountSrvice service = new CountSrvice();
		service.transMorney(1, 2, 200);
		System.out.println("OK....");
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值