52ky 发表于 2022-5-5 09:17:37

将数据帧写入 Postgres 数据库 psycop2

问题
我正在尝试将 pandas 数据框写入 Postgres 数据库。

代码显示如下:
dbConnection = psycopg2.connect(user = "user1", password = "user1", host = "localhost", port = "5432", database = "postgres")
dbConnection.set_isolation_level(0)
dbCursor = dbConnection.cursor()
dbCursor.execute("DROP DATABASE IF EXISTS FiguresUSA")
dbCursor.execute("CREATE DATABASE FiguresUSA")
dbCursor.execute("DROP TABLE IF EXISTS FiguresUSAByState")
dbCursor.execute("CREATE TABLE FiguresUSAByState(Index integer PRIMARY KEY, Province_State VARCHAR(50), NumberByState integer)");

for i in data_pandas.index:
    query = """
    INSERT into FiguresUSAByState(column1, column2, column3) values('%s',%s,%i);
    """ % (data_pandas['Index'], data_pandas['Province_State'], data_pandas['NumberByState'])

dbCursor.execute(query)

当我运行它时,我得到一个错误,它只是说:“索引”。我知道这是我的 for 循环中某处的问题,这个 % 符号是否正确?我是 Postgres 的新手,不知道它怎么可能是正确的语法。任何人都可以帮忙吗?我知道我可以使用 sql,但我正在尝试一种不同的技术。

数据打印如下:

一个轻微的例外是有一个“索引”。在 IDE 版本中。这可能是问题吗?

回答
如果使用 pd.DataFrame.to_sql,您可以提供 index_label 参数以将其用作列。

data_pandas.to_sql('FiguresUSAByState', con=dbConnection, index_label='Index')

如果您希望坚持使用现有的自定义 SQL 和 for 循环,则需要先重置索引。

for row in data_pandas.reset_index().to_dict('rows'):
    query = """
    INSERT into FiguresUSAByState(index, Province_State, NumberByState) values(%i, '%s', %i);
    """ % (row['index'], row['Province_State'], row['NumberByState'])
请注意,新列的默认名称是未大写的 index ,而不是 Index 。



页: [1]
查看完整版本: 将数据帧写入 Postgres 数据库 psycop2