我在理解Python语言中psycopg3库的适当语法时遇到了一些困难。我正在尝试将.csv文件的内容复制到我的数据库中。The PostgreSQL documentation表示copy的写法如下:
COPY table_name [ ( column_name [, ...] ) ]
FROM { 'filename' | PROGRAM 'command' | STDIN }
[ [ WITH ] ( option [, ...] ) ]
[ WHERE condition ]所以我把我的python语句写成如下:
import psycopg
with psycopg.connect('dbname=ideatest user=postgres password=password') as conn:
with conn.cursor() as cur:
mock_idea_info = open(r'C:\dir\filename.csv')
cur.copy('public.ideastorage FROM C:\dir\filename.csv;')
print('Copy successful.')问题是脚本打印“复制成功”,但没有将数据插入到数据库中。不会生成错误消息。我在文件路径中复制了\字符,所以这不是问题所在。我一直在寻找解决方案和可能的故障排除方法,但还没有找到任何我所理解的似乎相关的东西。
此外,是否可以将mock_idea_info直接传递到copy语句中?
任何帮助都将不胜感激。
发布于 2021-11-06 00:02:19
请参阅Copy from
cat data.out
1 2
2 1
\d csv_test
Table "public.csv_test"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
col1 | integer | | |
col2 | integer | | |
with open("data.out", "r") as f:
with cur.copy("COPY csv_test FROM STDIN") as copy:
while data := f.read(100):
copy.write(data)
con.commit()
select * from csv_test ;
col1 | col2
------+------
1 | 2
2 | 1
--Add format options
cat data.out
1,2
2,1
with open("data.out", "r") as f:
with cur.copy("COPY csv_test FROM STDIN WITH (FORMAT CSV)" ) as copy:
while data := f.read(100):
copy.write(data)
con.commit()
select * from csv_test ;
col1 | col2
------+------
1 | 2
2 | 1
1 | 2
2 | 1以上改编自link中的示例。此while data := f.read(100)使用仅在Python 3.8+中提供的海象(:=
发布于 2021-11-06 00:22:25
我没有看到您在输入之后提交将数据持久化到数据库中。尝试添加以下内容:
conn.commit()发布于 2021-11-06 20:12:26
您可能应该包含with (format csv)子句(请参见https://www.postgresql.org/docs/current/sql-copy.html),或者显式指定引号和分隔符字符。
https://stackoverflow.com/questions/69860284
复制相似问题