欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

addBatch()和executeBatch()批量添加和单个添加效率一样

程序员文章站 2022-07-13 09:08:49
...

原因:数据库默认没完成一次操作就自动提交一次commit(),
所以在添加开始时先connection.setAutoCommit(false);
然后在添加结束后connection.commit();

例如:

    @Test
    public void lotInsert() throws Exception {
        JDBCUtil util = new JDBCUtil();
        Connection connection = null;
        java.sql.PreparedStatement ps = null;

        try {
            connection = util.Connection();
            //取消每次操作都提交,必须有否则和单个添加一样
            connection.setAutoCommit(false);
            String sql = "insert into goods(name) value(?);";
            ps = connection.prepareStatement(sql);
            long begin = System.currentTimeMillis();
            //批量添加
            for (int i = 1; i <= 2000; i++) {
                ps.setObject(1 , "name_" + i);
                ps.addBatch();

                if(i % 500 == 0){
                    ps.executeBatch();
                    connection.commit();
                    ps.clearBatch();
                }

            }
            //最后再提交
            connection.commit();
            long end = System.currentTimeMillis();
            System.out.println(end - begin);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            util.Close(connection , ps);
        }
    }