Search code examples
pythonsqlpython-3.xcsvpymysql

Inserting specific information from CSV to SQL python3


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  

Solution

  • 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)