使用 psycopg2 大容量插入数据帧(错误:'dict'对象不支持索引)



非常感谢,psycopg2相对较新。

我正在尝试以pandas数据帧的形式将数据大容量插入到我现有的postgres数据库中。

try:
psycopg2.extras.execute_values(
cur=cur,
sql=sql.SQL("""
INSERT into {table_name} ( {columns} )
VALUES %s
""").format(table_name=Identifier(entity),
columns=SQL(', ').join(map(Identifier, column_names))
),
argslist=dataframe,
template=None,
page_size=500)
except Exception as error:
print(ERROR: ' + error)

当我运行这个时,我得到以下错误:

string index out of range

我尝试将数据帧更改为dict,使用:

dataframe = dataframe.to_dict(orient='records')

我从except子句得到的输出如下:

'dict' object does not support indexing

非常感谢任何帮助,我不确定这里的问题是什么。

提前感谢

这似乎是一个没有帮助的错误消息。引用另一个SO的答案:

您必须给定%%才能将其用作%,因为python中的%用作字符串格式,所以当您编写单个%时,它假设您将用它替换一些值。

所以,当您想在带查询的字符串中放置单个%时,总是放置双%

请尝试以下代码,该代码将%s替换为%%s

try:
psycopg2.extras.execute_values(
cur=cur,
sql=sql.SQL("""
INSERT into {table_name} ( {columns} )
VALUES %%s
""").format(table_name=Identifier(entity),
columns=SQL(', ').join(map(Identifier, column_names))
),
argslist=dataframe,
template=None,
page_size=500)
except Exception as error:
print(ERROR: ' + error)

或者,您可以使用pandas.to_sql:

from sqlalchemy import create_engine
engine = create_engine('"postgresql://postgres:postgres@localhost/postgres"', echo=False)
df.to_sql('table_name', con=engine, if_exists='append')

在生产中尝试之前先玩一玩。。。

最新更新