我在这段代码中找不到错误:
sql = "INSERT INTO diff (val) VALUES (%s)"
test = '99'
mycursor.execute(sql, test)
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 '%s)' at line 1
有人可以向我解释吗?预先感谢!
答案 0 :(得分:1)
如果可以描述所使用的数据库连接器,将有所帮助,但是您可以尝试以下操作:
如果该值是字符串,请尝试用引号将%s包裹起来
"INSERT INTO diff (val) VALUES ('%s')"
您可能需要使execute函数的第二个参数为元组,即
mycursor.execute(sql, (test,))
您的连接器可能还支持关键字参数
mycursor.execute("INSERT INTO diff (:val)", {'val': '99})
答案 1 :(得分:0)
我在设备上遇到了同样的错误。我用
测试了直接SQL
插入diff(val)值('99');
起作用了。
当我按照https://stackoverflow.com/users/6837068/james-wu的建议使用''时,错误停止,但是插入将插入0,直到将列更改为varchar,然后插入了'%s'而不是'99'。
我发现还有另一种分配变量的方法。
有关更多信息,请参见https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html。
示例代码如下。
#!/usr/bin/env python
import mysql.connector # pip install mysql-connector-python
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(user='root', host='localhost',database='stackoverflow_53346780',use_pure=True)
cursor = connection.cursor()
#https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html
sql = "INSERT INTO diff (val) VALUES (%(val)s) ;"
test = {'val':'99'}
cursor.execute(sql, test)
connection.commit()
cursor.close()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
connection.close()
结果
select * from diff ;
1 99
4 0
5 0
6 %s
7 99
8 99