Python PostgreSQL "error insert has more target columns than expressions"但它不是



我是SQL和PostgreSQL的新手,我不明白这段代码是怎么回事。

我试图使用以下代码将 csv 插入到帖子中:

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-00000000000 1580463062 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000但这是我想插入的 ['00000000-0000-0000-0000-0000000000000', '00000000-0000-0000-0000000000000000000000000000000000000000000000000000000000 1580463062 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 它看起来肯定有 4 列

我还尝试将 csv 的编码从 ASCII 更改为 UTF-8 和 UTF-8_SIG,但我仍然收到此错误

我用这段代码解决了我的问题

import psycopg2
conn = psycopg2.connect("host=host dbname=dbname user=user 
password=password")
cur = conn.cursor()
with open(filename, 'r') as f:
next(f)
cur.copy_from(f, 'auth', sep=',')
conn.commit()
cur.close()
conn.close()

相关内容

最新更新