我的python中有一个语法错误,它阻止MySQLdb插入我的数据库。 SQL插入在下面。
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
我的堆栈跟踪中出现以下错误。
_mysql_exceptions.ProgrammingError: (1064, "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 ''four' (description, url) VALUES ('', 'http://imgur.com/a/V8sdH')' at line 1")
我真的很感激,因为我无法理解这一点。
编辑:
使用以下行修复它:
cursor.execute("INSERT INTO " + table_name + " (description, url) VALUES (%s, %s);", (key.encode("utf-8"), data[key].encode("utf-8")))
不是最复杂的,但我希望将它作为跳跃点。
答案 0 :(得分:3)
看起来这是你的SQL语句:
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
IIRC,name of the table is not able to be parameterized(因为它被引用不当)。您需要以其他方式将其注入字符串中(最好是安全地 - 通过检查所请求的表名与列入白名单的表名集匹配)...例如:
_TABLE_NAME_WHITELIST = frozenset(['four'])
...
if table_name not in _TABLE_NAME_WHITELIST:
raise Exception('Probably better to define a specific exception for this...')
cursor.execute("INSERT INTO {table_name} (description, url) VALUES (%s, %s);".format(table_name=table_name),
(table_name.encode("utf-8"),
key.encode("utf-8"),
data[key].encode("utf-8")))