Java JDBC批处理 批量提交

什么是JDBC批处理

JDBC批处理,意思是我们可以执行一批(组)SQL操作。批处理可以使数据库执行性能更快。

java.sql.Statement和java.sql.PreparedStatement接口都提供了用于批处理的方法。

一、批处理使用场景:

        在实际业务场景中,我们需要批量修改的时候恰好还有where条件,导致我们只能一条一条提交,没提交一次,又要获取一次jdbc连接,如果是十几条还好,但是上百条,就导致了响应速度慢。那么批处理就是解决这个问题,获取一次连接,然后把多条sql拼接成一条去执行。

二、上代码:

 封装成了一个工具类,dataSource需要在调用方法的时候提前获取一下项目的jdbc连接

import com.usmart.common.utils.StringUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;

/**
 * 批处理
 */
public class BatchProcessingUtils {


    /**
     * @return boolean
     * @MethoName sqlBatchExecuteCanRollback
     * @Param [dataSource:获取数据源,sql:拼接好的sql语句, batchSize:多少次提交异常]
     **/
    public boolean sqlBatchExecuteCanRollback(DataSource dataSource,StringBuffer sql, int batchSize) throws Exception {

        if(StringUtils.isBlank(sql) || sql == null){
            return false;
        }
        List<String> sqlList = Arrays.asList(sql.toString().split("-"));
        Connection connection = dataSource.getConnection();
        Statement statement = null;
        try {
            statement = connection.createStatement();
            connection.setAutoCommit(false);
            if (sqlList.size() <= batchSize) {
                for (int i = 0; i < sqlList.size(); i++) {
                    String s = sqlList.get(i);
                    statement.addBatch(s);
                }
                statement.executeBatch();
                connection.commit();
                return true;
            }
            if (sqlList.size() > batchSize) {
                for (int i = 0; i < sqlList.size(); i++) {
                    String s = sqlList.get(i);
                    statement.addBatch(s);
                    if (i != 0 && (i + 1) % batchSize == 0) {
                        statement.executeBatch();
                        statement.clearBatch();
                    }
                }
                statement.executeBatch();
                connection.commit();
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
                return false;
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                connection.close();
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return true;
    }






}

调用方法:

public class testServiceImpl {

    @Resource
    DataSource dataSource;

public void TestSqlList() {
        BatchProcessingUtils batchProcessingUtils = new BatchProcessingUtils();
        StringBuffer sqlList = new StringBuffer(); //批量提交用逗号分割
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> m1 = new HashMap<>();
        m1.put("id",1);
        m1.put("name","张三");
        m1.put("age","12");

        list.add(m1);


        Map<String, Object> m2 = new HashMap<>();
        m2.put("id",2);
        m2.put("name","李四");
        m2.put("age","20");
        list.add(m2);


        for (Map<String, Object> m : list){
            //结尾已;-结束 ,-用于转List切割使用 ,可根据自己的需求来自定义调整
            sqlList.append("update student set name ="+m.get("name")+" ,age = "+m.get("age")+" where id="+m.get("id")+";-");
        }
        try {
            //使用批处理 (获取数据源,拼装的sql,每500条提交一次)
            batchProcessingUtils.sqlBatchExecuteCanRollback(dataSource,sqlList , 500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值