Python MySQLdb 变量作为表名

Tim*_*iam 2 python mysql

我的 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"))) 
Run Code Online (Sandbox Code Playgroud)

我的堆栈跟踪中出现以下错误。

_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")
Run Code Online (Sandbox Code Playgroud)

我非常感谢您的帮助,因为我无法弄清楚这一点。

编辑:

使用以下行修复它:

cursor.execute("INSERT INTO " + table_name + " (description, url) VALUES (%s, %s);", (key.encode("utf-8"), data[key].encode("utf-8")))
Run Code Online (Sandbox Code Playgroud)

不是最复杂的,但我希望用它作为起点。

mgi*_*son 7

看起来这是你的 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")))
Run Code Online (Sandbox Code Playgroud)

IIRC,表的名称无法参数(因为它的引用不正确)。您需要以其他方式将其注入到字符串中(最好是安全地——通过检查请求的表名是否与列入白名单的表名集匹配)...例如:

_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")))
Run Code Online (Sandbox Code Playgroud)