04 jdbc 批处理

批处理的API:
Statement的批处理:

void addBatch(String sql)  把sql添加到缓存区中(没有发送的)
int[] executeBatch()  执行批处理缓存中sql语句(发送到数据库执行)
void clearBatch()  清空缓存区sql语句

PreparedStatement的批处理:

void addBatch()   把参数添加到缓存区中
int[] executeBatch()  执行批处理缓存中所有参数(发送到数据库执行)
void clearBatch()  清空缓存区参数列表

代码演练:
PrepaedStatement执行批处理


    public static void testByPreparedStaementBatch(){
        Connection conn = null;
        PreparedStatement stmt = null;
        try{
            conn = JdbcUtil.getConnection();
            stmt = conn.prepareStatement("INSERT INTO student VALUES(?,?,?,?)");
            for(int i=1;i<=2000;i++){
                //参数赋值
                stmt.setInt(1, i);
                stmt.setString(2, "张三");
                stmt.setInt(3, 20);
                stmt.setString(4, "男");
                //把参数添加到缓存区
                stmt.addBatch();
                //每20次发送一次参数
                if(i%20==0){
                    //执行批处理命令
                    stmt.executeBatch();
                    //清空缓存区的参数
                    stmt.clearBatch();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtil.close(stmt, conn);
        }
    }

statement执行批批处理

public static void testByStaementBatch(){
        Connection conn = null;
        Statement stmt = null;
        try{
            conn = JdbcUtil.getConnection();
            stmt = conn.createStatement();
            for(int i=1;i<=2000;i++){
                //把sql添加到缓存区
                stmt.addBatch("INSERT INTO student VALUES("+i+",'张三',20,'男')");
                //每20条发送sql
                if(i%20==0){
                    //执行批处理命令
                    stmt.executeBatch();
                    //清空缓存区
                    stmt.clearBatch();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtil.close(stmt, conn);
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本节介绍Statement接口及其子类PreparedStatement和CallableStatement。 它...
    zlb阅读 4,890评论 0 0
  • 本人的环境为Myeclipse10、MySQL5.7.15 本文包括:简介JDBC编程步骤打通数据库程序详解—Dr...
    廖少少阅读 9,549评论 7 39
  • JDBC简介 SUN公司为了简化、统一对数据库的操作,定义了一套Java操作数据库的规范,称之为JDBC。JDBC...
    奋斗的老王阅读 5,410评论 0 51
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,906评论 18 399
  • 孩子咳嗽厉害,又吃很多零食,焦虑又来了,对孩子唠叨,说着说着最后发展到厉声说教。 讲完睡前故事我感觉整个气氛都很压...
    书媛jy阅读 4,781评论 0 1