【问题标题】:Python PostgreSQL "error insert has more target columns than expressions" but its notPython PostgreSQL“错误插入的目标列多于表达式”,但不是
【发布时间】: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


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 2015-02-22
    • 2021-12-20
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    相关资源
    最近更新 更多