![](/img/trans.png)
[英]Python/MySQL How to insert a String using a variable, keeps changing “TRUE” to 1
[英]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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.