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....");
}
QueryRunner 事务,转账
最新推荐文章于 2022-04-20 14:55:09 发布