jdbc 数据库批处理insert操作

为君一笑 提交于 2019-12-04 09:16:52
package blob;

import java.sql.Connection;
import java.sql.PreparedStatement;
import jdbc.utils.*;
//使用PreparedStatement实现更高效的批量插入
//如果不能使用batch方法,在url最后添加 ?rewriteBatchedStatements=true
public class InsertTest {
    static public void testInsert2() {
        Connection con = null;
        PreparedStatement ps = null;
        try {
            con = JDBCUtils.getConnection();
            String sql = "insert into good values(?,?)";
            ps = con.prepareStatement(sql);
            
            //不允许自动提交数据
            con.setAutoCommit(false);
            
            for(int i=1;i<=20000;i++) {
                ps.setInt(1, i);
                ps.setString(2, "good_");
                ps.addBatch();//使用批处理Batch来暂存数据
                if(i%500 == 0) {//再一起放到数据库里
                    ps.executeBatch();
                    ps.clearBatch();
                }
            }
            
            //最后统一提交数据
            con.commit();
            
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        finally {
            JDBCUtils.closeResource(con, ps);
        }
    }
    
    public static void main(String[]args) {
        testInsert2();
    }
}

1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!