0

I wish to import my .csv file to a table 'testcsv' in MySQL using Python, but I'm unable to do so because I keep getting the following error:

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

My code looks like this:

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)

I've tried every possible answer given to the related questions here, but none of them worked for me. Please help!

1 Answer 1

1
for r in range(1, row_count):

just iterates over numbers, i.e. in the first iteration r = 1. Remove the line defining row_count and get the actual rows:

for r in csv_data:
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.