Python loading a set of .csv files into MySQL

I am using following command to load multiple .csv files into Mysql database but i am getting no errors on (the IDLE window) and the data does not load

Here is the erroneous script

#!C:\Python27\python.exe

import MySQLdb
import os
import string

# Open database connection
db = MySQLdb.connect (host="localhost",port=3307,user="root",\
                      passwd="gamma123",db="test")

cursor=db.cursor()


l = os.listdir(".")
for file_name in l:
        print file_name
        cursor=db.cursor()
        if (file_name.find("DIV.csv")>-1):
           #Query under testing
            sql = """LOAD DATA LOCAL INFILE file_name \
            INTO TABLE system_work \
            FIELDS TERMINATED BY ',' \
            OPTIONALLY ENCLOSED BY '"'  \
            LINES TERMINATED BY '\r\n' \
            IGNORE 1 LINES;;"""
try:
            # Execute the SQL command
            cursor.execute(sql)
            # Commit your changes in the database
            db.commit()
except:
            # Rollback in case there is any error
            db.rollback()

# disconnect from server
db.close()

But when i try to load a single file using the following python script then its works fine. please help....

#!C:\Python27\python.exe

import MySQLdb
import os
import string

# Open database connection
db = MySQLdb.connect (host="localhost",port=3307,user="root",\
                      passwd="gamma123",db="test")

cursor=db.cursor()

#Query under testing
sql = """LOAD DATA LOCAL INFILE 'Axle.csv' \
      INTO TABLE system_work \
      FIELDS TERMINATED BY ',' \
      OPTIONALLY ENCLOSED BY '"'  \
      LINES TERMINATED BY '\r\n' \
      IGNORE 1 LINES;;"""

try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()

Upvotes: 1

Views: 7852

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125058

You need to interpolate the filename into the SQL string; you are just sending the literal text file_name to the server. You could use the str.format() method for that, any {} placeholder can then be replaced by a variable of your choosing.

You also must indent the try and except blocks to be within the for loop:

sql = """LOAD DATA LOCAL INFILE '{}'
INTO TABLE system_work
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\\r\\n'
IGNORE 1 LINES;;"""

for file_name in l:
    print file_name
    if file_name.endswith('DIV.csv'):
        try:
            cursor = db.cursor()
            cursor.execute(sql.format(file_name))
            db.commit()
        except Exception:
            # Rollback in case there is any error
            db.rollback()

The cursor.execute() method is passed the sql string with the file_name variable interpolated. The {} part on the first line (LOAD DATA LOCAL INFILE '{}') will be replaced by the value in file_name before passing the SQL statement to MySQL.

I also simplified the filename test; presumably it is enough if the filename ends with DIV.csv.

Note that it might just be easier to use the mysqlimport utility; you can achieve the exact same results with:

mysqlimport --fields-terminated-by=, --fields-optionally-enclosed-by=\" \
            --local --lines-terminated-by=\r\n --user=root --password=gamma123 \
            test *DIV.csv

Upvotes: 7

norlesh
norlesh

Reputation: 1861

if (file_name.find("DIV.csv")>-1): unless all of your files are actually called DIV.csv should that be if (file_name.find(".csv")>-1): (that would probably be more efficient testing the last four letters of the file name by the way)

Upvotes: 1

Related Questions