【问题标题】:Insert values from csv file with no header to a SQL table with headers将不带标题的 csv 文件中的值插入到带标题的 SQL 表中
【发布时间】:2022-01-31 00:06:38
【问题描述】:

我有一个没有标题的 csv 文件,并创建了一个包含字段 A、B、C、D 和 E 的 SQL 表。我需要将 csv 文件中的数据导入 python 上的表中。

file = open(path)
data = csv.reader(file)
cursor = connection.cursor()
query = '''INSERT INTO table (id1, id2, name, birthday, score) VALUES (?,?, ?,?,?)'''
cursor.executemany(insert_movies, data)
cursor.close()
connection.commit()

我也尝试过遍历行

file = open(path)
data = csv.reader(file)
cursor = connection.cursor()
query = '''INSERT INTO table (id1, id2, name, birthday, score) VALUES (?,?, ?,?,?)'''
for row in data:
    cursor.executemany(query, row)
connection.commit()

【问题讨论】:

  • 您向我们展示了一些代码。没有做你想做的事怎么办?您收到错误消息吗?请阅读How to Ask
  • 请注意,您的表格有,而不是字段。

标签: python sql csv


【解决方案1】:

我在 Jupyter 而不是可视代码上运行了它,它运行了。实际上,该表的输出正在输入另一个未显示任何元素的表。但是在 Jupyter 上运行后,相同的代码生成了该表。不知道真正的原因是什么。

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 2014-11-23
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2017-10-15
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多