转账逻辑

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>() {
			@Override
			public 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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值