【发布时间】:2020-09-17 12:16:36
【问题描述】:
我是 SQL 和 PostgreSQL 的新手,我无法理解这段代码发生了什么。
我正在尝试使用此代码将 csv 插入 postgres:
import csv
import psycopg2 as pg
filename = 'myfile.csv'
try:
conn = pg.connect(user="myuser",
password="mypass",
host="myhost",
port="5432",
database="mydb")
cursor = conn.cursor()
with open(filename, 'r') as f:
reader = csv.reader(f)
next(reader) # This skips the 1st row which is the header.
for record in reader:
print(record)
cursor.execute("""INSERT INTO auth VALUES (%s, %s, %s, %s)""", record)
conn.commit()
except (Exception, pg.Error) as e:
print(e)
finally:
if (conn):
cursor.close()
conn.close()
print("Connection closed.")
但它会引发 错误插入的目标列多于表达式 第 1 行:...00000000-0000-0000-0000-000000000000', '1580463062', 'auto')
但这是我要插入的内容 ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-0000000000000', '1580463062', '自动'] 它看起来肯定有 4 列
我也尝试将 csv 的编码从 ASCII 更改为 UTF-8 和 UTF-8_SIG 但我仍然收到此错误
【问题讨论】:
-
"""INSERT INTO....)""", (record[0], record[1],record[2],record[3]))
-
cursor.execute() 最多接受 2 个参数。但我也试过 cursor.execute("""INSERT INTO auth VALUES ({}, {}, {}, {})""".format(record[0], record[1],record[2 ],record[3]) 我仍然得到这个错误
-
抱歉,需要将记录用括号括起来,请查看文档psycopg.org/docs/usage.html
-
@Chris 还是不行,我什至试着让它像这样 ...VALUES (%s, %s, %s, %s)""", (' 00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '1580463062', 'auto') 但得到这个错误。我在 postgres 的表中有 4 个文本列
标签: python postgresql