0

To go more in depth into a question like this:

How to store text file into MySQL database using python

I have data that I am uncertain what it will be until my Python script reads the file. So the error I am getting is:

MySQLdb._exceptions.ProgrammingError: not enough arguments for format string

Here's my code:

file = open('./ftp_files/ReadMe.txt', 'r')
file_content = file.read()
for line in file_content:
fields = line.split('|')
file.close()

query = "INSERT INTO ICLN_LOADER_JOB_LOG (JOB_ID, LOADER_HOST_NAME, MYSQL_HOST_NAME) VALUES ('%s', '%s', '%s')"

cursor.execute(query, (file_content,))

I understand that normally you would have the data values after %s... but what if I don't know what those values are, how can I set it up so that Python reads what the file content is and fills in the gaps?

2 Answers2

0

That depends how you defined the table ICLN_LOADER_JOB_LOG

IF LOADER_HOST_NAME and MYSQL_HOST_NAME alloow NULL as Value. you can do this

query = """INSERT INTO ICLN_LOADER_JOB_LOG (JOB_ID, LOADER_HOST_NAME, MYSQL_HOST_NAME) 
         VALUES ('%s', NULL, NULL)"""

cursor.execute(query, (file_content,))

Also you could use instead of NULL other values that mark , the columns had no value

Like

query = """INSERT INTO ICLN_LOADER_JOB_LOG (JOB_ID, LOADER_HOST_NAME, MYSQL_HOST_NAME) 
         VALUES ('%s', '%s', '%s')"""
lhn = '';
myhn = '';
cursor.execute(query, (file_content,lhn,mysn))
nbk
  • 45,398
  • 8
  • 30
  • 47
0

You can insert any values into a string using .format() method. But your problem should be that you are closing your file before you use file_content.

Malcador
  • 53
  • 9