【问题标题】:Python loop to create MYSQL insert into statements from data in the CSVPython循环从CSV中的数据创建MYSQL插入语句
【发布时间】:2018-04-05 17:11:39
【问题描述】:

我需要编写一个 python 代码,通过循环将 CSV 的所有条目转换为 mySQL insert into 语句。我有大约 600 万个条目的 csv 文件。

下面的这段代码可能可以读取一行。虽然有一些语法错误。由于我没有编码背景,因此无法准确指出。

file = open('physician_data.csv','r')
for row in file:
    header_string = row
header_list = list(header_string.split(','))
number_of_columns = len(header_list)
insert_into_query= INSERT INTO physician_data (%s)
for i in range(number_of_columns):
    if i != number_of_columns-1:
        insert_into_query+="%s," %(header_list[i])
    else:
        # no comma after last column
        insert_into_query += "%s)" %(header_list[i])

print(insert_into_query)
file.close

谁能告诉我怎么做?

【问题讨论】:

    标签: python mysql csv


    【解决方案1】:

    请在描述问题时包含错误消息 (https://stackoverflow.com/help/mcve)。

    您可能会发现CSV library 的文档很有帮助。

    在适当的地方使用引号,例如insert_into_query = "INSERT..."

    像这样调用关闭函数:file.close()

    【讨论】:

    • 错误是回溯,错误的操作数。看来我的语法是错误的。
    猜你喜欢
    • 2013-09-27
    • 2013-06-23
    • 2020-01-29
    • 2019-04-14
    • 2016-01-07
    • 2019-12-24
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多