繁体   English   中英

使用 Python 将 CSV 导入数据库

[英]Importing CSV into database using Python

我正在尝试使用 python 将 csv 文件导入连接的 MySQL 数据库。 但是,我不断收到以下错误: ProgrammingError: not enough arguments for format string。

所有代码运行完美,直到:“cursor.execute(”有人有什么想法吗?

使用的代码:

#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')

使用print(list(csv_data))检查csv_data变量的值,如果csv_data是迭代器或数据集很大,则使用print(repr(row))更好。

如评论中所述,该row没有足够的值来填充execute() function 的%s占位符,并且将失败。

这是有关正在发生的事情的更多详细信息- 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

并且由于占位符( %s )的计数大于用于格式化/模板化的值的计数,因此引发了TypeError

暂无
暂无

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

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