0

I have extracted filename from a certain directory. Filename is a string variable. Such as: 'LineNo-YYMMDD_hhmm'. Now I want to insert the filename into the existing MySQL DB. But couldn't find how to add as a str variable. This is what I had tried. Have some other way also checking net.

....

file_prefix = os.path.basename(name)[: - (len(filetail))]
(file_prefix is: LineName-200215_1619)
try: 
    connection = mysql.connector.connect(
                host='localhost', db = 'db_name', 
                user='usr', password='myPass')
   mysql_insert_query = " INSERT INTO fileHeader (headInfo) VALUES %s" % str(file_prefix)
   cursor = connection.cursor()
   cursor.execute(mysql_insert_query)
   connection.commit()
   cursor.close()

except mysql.connector.Error as error:
    print ("Failed to insert record into fileHeader table {}".format(error))

Getting the following error:

Failed to insert record into fileHeader table 1064 (42000): 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  
'LineName-200215_1619' at line 1 

1 Answer 1

1

add '' in your mysql_insert_query:

 mysql_insert_query = " INSERT INTO fileHeader (headInfo) VALUES ( '{0}')".format(file_prefix)
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks a lot.

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.