如何将文件名作为字符串变量插入 python 中的 mysql 数据库

how to insert filename as a string variable into mysql database in python

我已经从某个目录中提取了文件名。文件名是一个字符串变量。如:'LineNo-YYMMDD_hhmm'。现在我想将文件名插入现有的 MySQL 数据库中。但找不到如何添加为 str 变量。这是我试过的。还有其他方法也可以查网。

....

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

出现以下错误:

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 

在你的 mysql_insert_query 中添加 '':

 mysql_insert_query = " INSERT INTO fileHeader (headInfo) VALUES ( '{0}')".format(file_prefix)