我正在尝试(但失败了)使用 psycopg3 将数据从 .csv 文件复制到 postgres 表中。 它使用以下代码使用 psycopg2 完美运行:
tabname= 'rd2'
fname2='new_data.csv'
new_data.to_csv(fname2, index=None)
with open(fname2,'r') as y:
next(y)
cur.copy_from(y,tabname, sep=',')
conn.commit()
我已经阅读了 psycopg3 的文档:Psycopg3 Copy 和 Psycopg3 COPY_TO 和 COPY_FROM,我完全被难住了。 我尝试过的最新迭代(很多)是:
with open(fname, 'r') as f:
with cur.copy("copy rd2 from stdin") as copy:
data=next(f)
copy.write_row(data)
conn.commit()
给出以下错误:
Traceback (most recent call last):
Cell In[44], line 2
with cur.copy("copy rd2 from stdin") as copy:
File ~\Anaconda3\envs\spyder-env\Lib\contextlib.py:137 in __enter__
return next(self.gen)
File ~\Anaconda3\envs\spyder-env\Lib\site-packages\psycopg\cursor.py:903 in copy
raise ex.with_traceback(None)
InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block
我正在使用 Spyder 5 IDE 和 python 3.11
如果您的数据已经在数据框中,您可以尝试:
with io.StringIO() as sourceStream:
new_data.to_csv(sourceStream, sep="\t", header=False, index=False)
sourceStream.seek(0)
cur.copy_from(sourceStream, tabname)
cur.commit()