TypeError:使用Python将CSV导入MySQL时,格式字符串的参数不足

2024-09-28 22:20:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望使用Python将我的.csv文件导入MySQL中的表“testcsv”,但我无法这样做,因为我不断遇到以下错误:

Traceback (most recent call last):
  File "<pyshell#9>", line 2, in <module>
    cursor.execute(query,r)
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 184, in execute
    query = query % db.literal(args)
TypeError: not enough arguments for format string

我的代码如下所示:

import csv
import MySQLdb

mydb = MySQLdb.connect(host='127.0.0.1',
    port=3306,
    user='root',
    passwd='tulip',
    db='frompython')
cursor = mydb.cursor()

csv_data = csv.reader(file('C:\Users\Tulip\Desktop\New_Sheet.csv'))

row_count = sum(1 for row in csv_data)

query = """INSERT INTO testcsv (number, name, marks) VALUES (%s, %s, %s)"""

for r in range(1, row_count):
    cursor.execute(query,r)

我已经尝试了所有可能的答案来回答这里的相关问题,但是没有一个对我有用。请帮帮我!你知道吗


Tags: csvinimportforexecutedbdataline