简体   繁体   English

插入数据时的 MySQL 语法错误 (Python)

[英]MySQL Syntax error when inserting data (Python)

I have the following:我有以下几点:

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()

However, an error occurs in the in line where I do cursor.execute(...) .但是,在我执行cursor.execute(...)行中发生错误。 Specifically: 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 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

Printing out my dictionary reveals no extra parentheses at the end of the parsed_data["taste"] .打印出我的字典在parsed_data["taste"]的末尾没有显示额外的括号。 It seems like whatever reason, an extra parentheses is being added which is being interpreted by mySQL has actual SQL syntax?似乎无论出于何种原因,都会添加一个额外的括号,该括号由 mySQL 解释具有实际的 SQL 语法? I don't know why this is appearing.我不知道为什么会出现这种情况。

If the values are strings, you need quotes around them.如果值是字符串,则需要用引号将它们括起来。 But the correct solution is to use parameters in cursor.execute() rather than string formatting.但正确的解决方案是在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"])

That's your problem.那是你的问题。 You've got to quote your values.你必须引用你的价值观。 And python's string formatting doesn't do that.而python的字符串格式不会那样做。

VALUES ('%s', '%s')" % (parsed_data["category"], parsed_data["taste"])

This would probably work better, but even then that's a terrible solution prone to SQL Injection.这可能会更好,但即便如此,这也是一个容易发生 SQL 注入的糟糕解决方案。

Don't reinvent the wheel, use a SQL library for python.不要重新发明轮子,使用 Python 的 SQL 库。 We call those "ORM"s我们称这些为“ORM”

I personally love django's if that can help.如果有帮助的话,我个人喜欢 django。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM