jdbc 数据库批处理insert操作

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

猜你喜欢

转载自www.cnblogs.com/zsben991126/p/11852064.html