【发布时间】:2019-10-09 12:44:33
【问题描述】:
我正在尝试使用 python 将一个变量插入 mysql 数据库。但我有语法错误..你能帮帮我吗? :)
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='localhost',
database='Xiaomi_Temp',
user='user',
password='pass')
cursor = connection.cursor()
mySql_insert_query = """ INSERT INTO Temp_test (batt) VALUES (%d) """
recordTuple = (batt)
print(batt)
cursor.execute(mySql_insert_query, recordTuple)
connection.commit()
print("Record inserted successfully into table")
cursor.close()
except mysql.connector.Error as error:
print("Failed to insert record into table {}".format(error))
finally:
if (connection.is_connected()):
connection.close()
print("MySQL connection is closed")
我有变量 batt,它有整数值。 我的输出是:
Failed to insert record into table 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%d)' at line 1
MySQL connection is closed
【问题讨论】:
-
%d在 Python 中的字符串中用于格式化字符串以将%d替换为十进制值 - 例如,以下内容应该有效:"""INSERT INTO Temp_test (batt) VALUES (%d) """ % 12345(% 12345在end 告诉 python 用12345替换%d)。有关 python 字符串格式化的快速教程:learnpython.org/en/String_Formatting(请注意,此方法已弃用,首选str.format())
标签: python mysql mysql-python