我已经从某个目录中提取了文件名。文件名是一个字符串变量。例如:“ 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)