【问题标题】:Python and SQL: Getting rows from csv results in ERROR: "There are more columns in the INSERT statement than values specified in the VALUES clause."Python 和 SQL:从 csv 获取行会导致错误:“INSERT 语句中的列数多于 VALUES 子句中指定的值。”
【发布时间】:2021-09-11 08:01:04
【问题描述】:

我有一个 csv 文件,其中包含我试图通过 Python 脚本导入到 SQL 表中的几条记录。我的 csv 文件(现在简化为)只有一行 1。这是我正在尝试做的事情(在成功连接到数据库等之后......):

def add_records():
    with open('C:/testing/myCSV.csv') as csvFile:

        for row in csvFile:
            cursor.execute(
                "INSERT INTO MY_Table (thing1, thing2, thing3, thing4, thing5)"
                "VALUES (?)", row
            )

无论我如何格式化 csv 中的数据(现在都是 1),我都会收到错误:

INSERT 语句中的列数多于 VALUES 子句中指定的值

【问题讨论】:

  • ? 中的每个值都需要一个 ?
  • 在表格中插入 5 个值时使用 VALUES (?,?,?,?,?)
  • @mechanical_meat 用于每个目标列,因为解析器对row一无所知

标签: python sql pyodbc


【解决方案1】:

您需要在values 子句中为要插入的每一列指定一个值(或? 占位符):

cursor.execute(
    "INSERT INTO MY_Table (thing1, thing2, thing3, thing4, thing5)"
    "VALUES (?, ?, ?, ?, ?)", row
)

编辑:
row 只是从 CSV 文件中读取的简单行。您可能应该使用 csv reader 将其分解为各个组件:

with open('C:/testing/myCSV.csv') as csvFile:
    csvReader = csv.reader(csvFile)
    for row in csvReader:
        cursor.execute(
            "INSERT INTO MY_Table (thing1, thing2, thing3, thing4, thing5)"
            "VALUES (?, ?, ?, ?, ?)", row
        )

【讨论】:

  • @CJamesEd 您没有解析 CSV。查看我编辑的答案
【解决方案2】:
with open('C:/testing/myCSV.csv') as csvFile:
    factories = csv.reader(csvFile, delimiter=' ')
    for row in factories:
        cursor.execute(
            "INSERT INTO MY_Table (thing1, thing2, thing3, thing4, thing5)"
            "VALUES (?, ?, ?, ?, ?)", (''.join(row[0])), (''.join(row[1])), (''.join(row[2])), (''.join(row[3])), (''.join(row[4]))
        )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多