我正在使用copy_expert
中的方法psycopg2
将数据从 CSV 文件复制到 postgresql 表。我有这样的 postgres 表:
create table my_table (
cola text,
colb text,
colc text,
cold text,
cole text,
colf text,
colg text
)
还有一个包含前五列数据的 CSV,如下所示:
cola,colb,colc,cold,cole
1,foo,a,10,vvv
2,bar,b,20,www
3,baz,c,30,xxx
4,boo,d,40,yyy
5,baa,e,50,zzz
我想复制前五列的 CSV 数据,同时还指定colf
and colg
(每行应该具有相同的值colf
and colg
).
我可以将前五列复制到我的表中,如下所示:
conn = psycopg2.connect('dbname=name user=username')
cur = conn.cursor()
copy_sql = """
copy my_table (cola, colb, colc, cold, cole)
from stdin with
csv
header
delimiter as ','
"""
from_csv = '/path/to/data.csv'
with open(from_csv, 'r') as f:
cur.copy_expert(sql=copy_sql, file=f)
conn.commit()
cur.close()
如何使用 python 指定最后两列的值?我知道我可以在表 DDL 中指定默认值,如下所示:
create table my_table (
cola text,
colb text,
colc text,
cold text,
cole text,
colf text default 'foo',
colg text default 'bar'
)
但我想使用 python 添加值,因为每个 CSV 上传都有自己的值colf
and colg
,这些值是由我的 python 代码中的逻辑确定的。