Sqlalchemy mysql参数化查询

时间:2016-09-08 15:28:53

标签: python mysql sqlalchemy

我正在尝试将表名作为变量传递给sql查询并使用sqlalchemy游标执行它:

from sqlalchemy.sql import text

cur = DB_ENGINE.connect()
p = cur.execute(text('select * from :table'), {'table':'person'}).fetchall()
print p

我收到了此错误消息:

ProgrammingError: (_mysql_exceptions.ProgrammingError) (1064, "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 ''person'' at line 1") [SQL: u'select * from %s'] [parameters: ('person',)]

我哪里做错了?

1 个答案:

答案 0 :(得分:0)

占位符只能代表VALUES。您不能将它们用于sql关键字/标识符。

如果您需要动态更改标识符,那么您必须自己构建查询字符串,例如

sql = "SELECT foo FROM " + var_with_table_name + "WHERE somefield = ?"

然后让你开始使用SQL注入攻击来启动。