0

I am having some problems with inserting information from a CSV file to a SQL DB, This is the code I am using :

import csv 
import pymysql    

def sqlinsert(cur, vname, vid, file, db):                                                                 
    insertcsv = '''INSERT INTO `mydb`(VID,name,starttime,stoptime,sessiontime,calledstation,sessionbill)
                VALUES(%s, %s, %s, %s, %s, %s, %s)'''                                                                                                                                        
    with open(os.path.join(cwd, 'RawCSV', file), 'r') as f:                                               
        reader = csv.reader(f, delimiter='\t')                                                            
        next(reader)    # skipping the first line                                                                                  
        for row in reader:                                                                                
            cur.execute(insertcsv, (vid, vname, row[8:13]))                                                                                                               
            db.commit()                       

The issue is as follows :

TypeError: not enough arguments for format string    

If i will remove VID and name from the insert command and do it like this :

insertcsv = '''INSERT INTO `mydb (starttime,stoptime,sessiontime,calledstation,sessionbill) VALUES(%s, %s, %s, %s, %s)'''       
cur.execute(insertcsv, row[8:13])

This will import with no issues, What am I missing here?

this is the CSV line :

7869574006      1443580239  478 -00000027   1499347553.39   231     2017-07-06  
3
  • What does the first line of data look like? Commented Aug 8, 2017 at 12:06
  • Do you mean for the lines in the CSV? Commented Aug 8, 2017 at 12:07
  • That's what I mean. Commented Aug 8, 2017 at 12:11

1 Answer 1

1

1) Fix your indentation

2) (vid, vname, row[8:13]) will be a tuple of type (t1, t2, []). Where t1 & t2 are the type of vid & vname.

Try to use:

row_to_insert = [vid, vname] + row[8:13]    # Appending the two lists.
cur.execute(insertcsv, row_to_insert)
Sign up to request clarification or add additional context in comments.

2 Comments

Well that worked, thank you. i assume if i will want to add more rows than i can do something like " [vid, name] + row[8:13] + row[15:17]"
No problem, glad I could help! That should do it yes :)

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.