[英]MySQL Syntax error when inserting data (Python)
我有以下几点:
def insertion(database, data):
parsed_data = json.loads(data)
cursor = database.cursor()
cursor.execute("INSERT INTO Food (category, taste) VALUES (%s, %s)" % (parsed_data["category"], parsed_data["taste"]))
database.commit()
但是,在我执行cursor.execute(...)
行中发生错误。 具体来说: 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 'Sweet)' at line 1
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 'Sweet)' at line 1
。
打印出我的字典在parsed_data["taste"]
的末尾没有显示额外的括号。 似乎无论出于何种原因,都会添加一个额外的括号,该括号由 mySQL 解释具有实际的 SQL 语法? 我不知道为什么会出现这种情况。
如果值是字符串,则需要用引号将它们括起来。 但正确的解决方案是在cursor.execute()
使用参数而不是字符串格式。
cursor.execute("INSERT INTO Food (category, taste) VALUES (%s, %s)", (parsed_data["category"], parsed_data["taste"]))
VALUES (%s, %s)" % (parsed_data["category"], parsed_data["taste"])
那是你的问题。 你必须引用你的价值观。 而python的字符串格式不会那样做。
VALUES ('%s', '%s')" % (parsed_data["category"], parsed_data["taste"])
这可能会更好,但即便如此,这也是一个容易发生 SQL 注入的糟糕解决方案。
不要重新发明轮子,使用 Python 的 SQL 库。 我们称这些为“ORM”
如果有帮助的话,我个人喜欢 django。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.