Search code examples
pythonmysqlload-data-infile

MySQL LOAD DATA INFILE in Python not working using variable


I have a Python script in which I want to run LOAD DATA INFILE command.

I have a variable,

naseq_file = "../data/parsed/bga/Proma_str.MIT9215_nasequenceimp.parsed"

I am doing:

sql = """LOAD DATA LOCAL INFILE %s INTO TABLE nasequenceimp FIELDS TERMINATED BY '\t' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n';""" % (naseq_file)
try:
  c.execute(sql01)
  conn.commit()
except StandardError, e:
  print e
  conn.rollback()

Where naseq_file has the file name.

But it is showing error:

(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '../data/parsed/bga/Proma_str.MIT9215_nasequenceimp.parsed INTO TABLE nasequencei' at line 1")

What is wrong with my code?


Solution

  • Seems like you just need to wrap it in quotes.

    sql = """LOAD DATA LOCAL INFILE "%s" INTO ..."""