pandas 尝试将数据插入postgres数据库时出现psycopg2.errors.UndefinedColumn错误

yyyllmsg  于 2023-03-11  发布在  其他
关注(0)|答案(1)|浏览(340)

我有一个Pandas数据框架,其中有来自csv文件的数据。
我想将这些数据导入到我的postgres数据库中。

import pandas as pd
import psycopg2

# Import CSV, create Data Frame
data = pd.read_csv('my_csv.csv', delimiter=';')
df = pd.DataFrame(data)

# Prepare Data (Rename / Shorten Column-Headers)
columnsFromCSV = list(df.columns)
for i in columnsFromCSV:
    columnName = i.rsplit(None, 2)[0]
    df.rename(columns={i : columnName}, inplace=True)
df.columns = df.columns.str.lower()

# Connect to Database
conn = psycopg2.connect(
   database='database', user='postgres', password='admin', host='127.0.0.1', port= '5432'
)
cursor = conn.cursor() 

# Insert Data Frame into Database
for i in df.columns[1:]:
    cursor.execute('INSERT INTO counter (counterid) VALUES ({0})'.format(i))
    for j in range(365):
        cursor.execute('INSERT INTO measurements (counterid) VALUES({0})'.format(i))
conn.commit()
conn.close()

首先,我想在计数器表中存储每个计数器一次,然后我想将一年的每日测量值与计数器ID一起存储在测量值表中,稍后将插入每日测量值。
这就是我得到的错误消息:

Traceback (most recent call last):
  File "c:\EnergyCounter\EnergyCounter\backend\CSV_read_script.py", line 25, in <module>
    cursor.execute('INSERT INTO counter (counterid) VALUES ({0})'.format(i))
psycopg2.errors.UndefinedColumn: ERROR:  Column »counter1« does not exist 
LINE 1: INSERT INTO counter (counterid) VALUES (counter1)

已尝试使用小写、引用表名、使用“%s”而不是“.format”。

3htmauhk

3htmauhk1#

答案是使用命名参数:https://www.psycopg.org/docs/usage.html#passing-parameters-to-sql-queries
代码现在看起来像这样,它的工作:

# Insert Data Frame into Database
for i in df.columns[1:]:
    cursor.execute('''INSERT INTO counter (counterid) VALUES (%(columnName)s)''', {'columnName': i})
    for j in range(365):
        cursor.execute('''INSERT INTO measurements (counterid) VALUES(%(columnName)s)''', {'columnName': i})
conn.commit()
conn.close()

相关问题