JDBC 批量插入数据

如下

/**
 * @program: 批量插入数据
 * @description:
 * @author: Mr.Fan
 * @create: 2021-05-30 10:10
 **/
public class InsertTest {
    //批量插入
    @Test
    public void testInsert1() throws Exception {
        Connection conn = JDBCUtils.getConnection();
        String sql = "insert into list1(name)values(?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        for (int i = 1; i <= 20000; i++) {
            ps.setObject(1,"name" + i);

            ps.execute();
        }
        JDBCUtils.closeResource(conn, ps);
    }
    @Test
    public void testInsert2() throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {

            long start = System.currentTimeMillis();
            conn = JDBCUtils.getConnection();
            String sql = "insert into list1(name)values(?)";
            ps = conn.prepareStatement(sql);
            for (int i = 1; i <= 20000; i++) {
                ps.setObject(1,"name" + i);

                //攒sql
                ps.addBatch();

                if(i % 500 == 0){
                    //执行
                    ps.executeBatch();
                    //清空
                    ps.clearBatch();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println(end - start);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps);
        }
    }
	@Test
    public void testInsert3() {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            
            long start = System.currentTimeMillis();
            conn = JDBCUtils.getConnection();
            String sql = "insert into list1(name)values(?)";
            ps = conn.prepareStatement(sql);
            for (int i = 1; i <= 20000; i++) {
                ps.setObject(1,"name" + i);

                //攒sql
                ps.addBatch();

                if(i % 500 == 0){
                    //执行
                    ps.executeBatch();
                    //清空
                    ps.clearBatch();
                }
            }
            //提交数据
            conn.commit();

            long end = System.currentTimeMillis();
            System.out.println(end - start);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps);
        }
    }
}
posted @ 2021-07-17 23:00  子丶非鱼Zzz  阅读(317)  评论(0)    收藏  举报