简体   繁体   English

使用 Python 将 CSV 导入数据库

[英]Importing CSV into database using Python

I'm trying to import a csv file into a connecting MySQL database using python.我正在尝试使用 python 将 csv 文件导入连接的 MySQL 数据库。 However, I keep getting the following error: ProgrammingError: not enough arguments for format string.但是,我不断收到以下错误: ProgrammingError: not enough arguments for format string。

All code runs perfect until: "cursor.execute(" Does anybody have any ideas?所有代码运行完美,直到:“cursor.execute(”有人有什么想法吗?

Code used:使用的代码:

#Python connect with SQL
import MySQLdb
import csv
import sys

conn = MySQLdb.connect(host="127.0.0.1", user="root", password="", database="furniture")

print ("Connected with database")

cursor = conn.cursor()
csv_data = csv.reader(open(r"C:\Users\M.schuurman\Downloads\furniture2.csv"))
header = next(csv_data)

print('Importing the CSV Files')

for row in csv_data:
    print(row)
    cursor.execute(
        "INSERT INTO customer (customerid, customername, pcnumbers, pcletters, street,  number, province) VALUES (%s, %s, %s, %s, %s, %s, %s)", row)

conn.commit()
cursor.close()
print('Done')

Check the values of csv_data variable with print(list(csv_data)) or better with print(repr(row)) if csv_data is an iterator or the dataset is large.使用print(list(csv_data))检查csv_data变量的值,如果csv_data是迭代器或数据集很大,则使用print(repr(row))更好。

As mentioned in the comment, the row does not have enough values to fill the %s placeholders of execute() function and will fail.如评论中所述,该row没有足够的值来填充execute() function 的%s占位符,并且将失败。

Here's more details on what's happening - the mysqlclient 's cursors.BaseCursor.execute() attempts a "templated string %s, %s" % ("one value", ) which will raise a TypeError that gets renamed into ProgrammingError .这是有关正在发生的事情的更多详细信息- mysqlclientcursors.BaseCursor.execute()尝试"templated string %s, %s" % ("one value", ) ,这将引发TypeError重命名为ProgrammingError

>>> "templated string %s, %s" % ("one value", )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

and due to the count of placeholders ( %s ) being greater than the count of values for formating/templating the TypeError is raised.并且由于占位符( %s )的计数大于用于格式化/模板化的值的计数,因此引发了TypeError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM