首页 > 解决方案 > 无法使用 MySQL 连接器在 Python 中插入 INT 数据

问题描述

我在 Python 中使用 MySQL 连接器并尝试插入整数数据,但我不断收到此错误:

mysql.connector.errors.ProgrammingError: 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 '%s)' at line 1

我的代码如下所示:

medDosage = int(''.join(filter(str.isdigit, '42mg')))

myCursor.execute("INSERT INTO dosage (dosageDesc) VALUES (%s)", medDosage)
db.commit()

这个语句对所有其他变量都很好,但对于 INT 值,它不起作用。我尝试插入字符串变量而不是 int,但不起作用。还尝试转换值int(medDosage)以确保它是正确的类型,但仍然不起作用。我知道我的语法是正确的,所以我无法真正理解错误。你能帮忙解释一下为什么会出现这个错误吗?

先感谢您。

标签: pythonmysqlmysql-connector

解决方案


您需要确保最后一个参数是一个元组:

myCursor.execute("INSERT INTO dosage (dosageDesc) VALUES (%s)", (medDosage,))

推荐阅读