背景
上个月排查一个 Bug ,需要采集一张 PostgreSQL 的大表,测试时需要造数据。Python 比 Java 方便多了,所以用 Python写了一个批量插入 PostgreSQL 表的简单脚本。本文分享这个脚本,很简单的,就是利用 psycopg2
的 copy_from
完成批量插入 postgre 及其类似数据库的脚本。
之前网上找了好多脚本都没有能直接用的,尤其是 CSV 文件参数,自己尝试调了一下竟然通了,总结一下以备不时之需。
表结构创建
创建一个简单的人员信息的表 person_info 包含 几个简单的字段,SQL 创建脚本如下:
sql
drop table if exists person_info;
create table public.person_info
(
pk_uuid numeric(19) not null constraint person_info_pk primary key,
id varchar(20) not null,
name varchar(200) not null,
birthday varchar(20) not null,
address varchar(255) not null,
remark varchar(255),
create_time numeric(19) not null
);
生成CSV数据
按字段顺序生成 CSV 文件,这个可以用 Java 循环生成,按需要生成200万条数据。 Java的代码如下:
sql
public class DataGeneUtil {
public static void main(String[] args) {
int counter = 0;
String fileName = "/Applications/2025NewYear/mydata10.csv";
File outFile = new File(fileName);
try (FileWriter outFileWriter = new FileWriter(outFile, false)){
for(int i = 0;i<20000; i++) {
counter++;
if (counter % 5000 == 0) {
System.out.println("already write counter " + counter);
}
StringBuffer buffer = new StringBuffer();
buffer.append(i).append(",");//pk_uuid
buffer.append("i").append(",");//ID
buffer.append("张三").append(i).append(",");//name
buffer.append("1990-01-01").append(",");//birthday
buffer.append("地球村2号").append(",");//address
buffer.append("test").append(",");//remark
buffer.append(System.currentTimeMillis()).append("\n");//remark
outFileWriter.write(buffer.toString());
}} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
编写 Python 脚本
python
import psycopg2
# 连接数据库
conn = psycopg2.connect(dbname='xx', user='xx', password='xx',host='192.xx.xx.x',port='7700')
# 创建一个cursor对象
cur = conn.cursor()
#配置 CSV 路径,读取后写入
csvDataFile= '/Applications/2025NewYear/mydata10.csv'
tableColumn=("pk_uuid", "id", "name", "address", "birthday", "remark","create_time")
with open(csvDataFile, 'r') as f:
cur.copy_from(f, 'person_info', sep=',', columns=tableColumn)
# 提交事务
conn.commit()
# 关闭cursor和连接
cur.close()
conn.close()
脚本运行结果: 查看数据库插入结果:
注意事项:
- 关键点
copy_from
后面第一个参数是一个 CSV 文件,最初搜到很多信息都是使用io.StringIO
创建一个内存中的文件对象的,反复尝试都执行失败。后面找到一个介绍方法,直接传递文件,才形成本文这个脚本。此外还找到了一个比较齐全的文章《psycopg2中copy_to /copy_from/copy_expert的使用方法》 记录下来,以供参考。 - 需要先使用
pip install psycopg2
安装数据库操作模块。
启示录
实际上,这个批量插入 PostgreSQL 的脚本确实非常简单,对比之下 Java 的 JDBC 批量插入就繁琐多了!
同时还需要测试 Oracle 和 MySQL 的批量入库,这个两个数据库的批量入库脚本也写过,之后会一起整理出来。