转账逻辑

来源:互联网 发布:sql find 函数 编辑:程序博客网 时间:2024/04/28 00:25
package com.softeem.batch;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import com.softeem.utils.DAOHelper;import com.softeem.utils.DAOHelper.CallBack;import com.softeem.utils.DBConnection;/** * 批量操作一般为批量更新操作(insert,update) * 物理删除:从数据库表彻底删除(delete) * 逻辑删除:将被删除记录行指定字段标记位删除状态(隐藏)(update) * @author mrchai * */public class TestBath {public void batch1() throws SQLException{String sql1  = "insert into tbuser(username,password) values('jack','jack123')";String sql2  = "insert into tbuser(username,password) values('rose','rose123')";String sql3  = "insert into tbuser(username,password) values('tom','tom123')";String sql4  = "update tbuser set password='888888' where id>10"; Connection conn = DBConnection.getConn();Statement stmt = conn.createStatement();//将需要执行的sql语句加入到执行队列stmt.addBatch(sql1);stmt.addBatch(sql2);stmt.addBatch(sql3);stmt.addBatch(sql4);//批量执行int[] i = stmt.executeBatch();for (int j : i) {System.out.println("执行结果:"+j);}}public void batch2() throws SQLException{Connection conn = DBConnection.getConn();PreparedStatement ps = conn.prepareStatement("insert into tbuser(username,password) values(?,?)");for (int i = 0; i < 10000; i++) {ps.setString(1, "admin"+i);ps.setString(2, "123456");ps.addBatch();if(i % 100 == 0){ps.executeBatch();//先执行一波更新ps.clearBatch(); //清空缓冲区}}ps.executeBatch();}//查询指定账号的余额public double getCash(int id){double d = DAOHelper.queryOne("select cash from tbaccount where id=?",new CallBack<Double>() {@Overridepublic Double getData(ResultSet rs) {try {if(rs.next()){return rs.getDouble(1);}} catch (SQLException e) {e.printStackTrace();}return 0.0;}},id);return d;}//事务public void batch3(int a,int b,double cash) throws SQLException{Connection conn = DBConnection.getConn();//分别查询出a账号和b账号的余额double acash = getCash(a);double bcash = getCash(b);PreparedStatement ps = conn.prepareStatement("update tbaccount set cash=? where id=?");ps.setDouble(1, acash-cash);ps.setInt(2, 10);ps.addBatch();ps.setDouble(1, bcash+cash);ps.setInt(2, b);ps.addBatch();int[] i = ps.executeBatch();for (int j : i) {System.out.println("执行结果:"+j);}}public static void main(String[] args) throws SQLException {new  TestBath().batch3(1,2,10000);}}

原创粉丝点击