您可以通过如下四种方法进行批量插入数据。

  • 使用 的方法。
  • 使用 values(),(),…(); 的方法。
    1. postgres=# insert into tbl1 (id,info,crt_time) values (1,'test',now()), (2,'test2',now()), (3,'test3',now());
    2. INSERT 0 3
  • 使用 BEGIN; …多条insert…; END; 的方法。严格来说,这不属于批量,但可以减少事务提交时的同步等待,同样可以提升性能。
  • 使用 copy 协议。copy 协议与 insert 协议不一样,更加精简,插入效率高。
    1. test03=# \d test
    2. Table "public.test"
    3. ----------+-----------------------------+-----------
    4. id | integer | not null
    5. crt_time | timestamp without time zone |
    6. Indexes:
    7. "test_pkey" PRIMARY KEY, btree (id)
    8. test03=# copy test from stdin;
    9. Enter data to be copied followed by a newline.
    10. End with a backslash and a period on a line by itself.
    11. >> 8 'test' '2017-01-01'
    12. >> 9 'test9' '2017-02-02'
    13. COPY 2
    1. test03=# delete from test using (values (3),(4),(5)) as tmp(id) where test.id=tmp.id;
    2. DELETE 3
    3. test03=# select * from test;
    4. id | info | crt_time
    5. ----+---------+----------------------------
    6. 1 | new1 | 2017-04-24 15:58:55.610072
    7. 2 | new2 | 2017-04-24 15:28:20.37392
    8. 6 | new6 | 2017-04-24 15:59:12.265915

如果要清除全表,建议您使用 truncate。