我可以使用查询参数插入表名吗?
我有一个SQL炼金术引擎,我尝试通过sqlalchemy.sql.text插入参数以防止SQL注入。
以下代码有效,其中我为条件和条件值编码变量。
from sqlalchemy import create_engine
from sqlalchemy.sql import text
db_engine = create_engine(...)
db_engine.execute(
text(
'SELECT * FROM table_name WHERE :condition_1 = :condition_1_value'), condition_1="name", condition_1_value="John"
)
).fetchall()
但是,当我尝试为table_name
的变量名称编码时,它会返回错误。
from sqlalchemy import create_engine
from sqlalchemy.sql import text
db_engine = create_engine(...)
db_engine.execute(
text(
'SELECT * FROM :table_name WHERE :condition_1 = :condition_1_value'), table_name="table_1", condition_1="name", condition_1_value="John"
)
).fetchall()
有什么想法为什么这不起作用?
编辑: 我知道这与table_name
不是字符串有关,但我不确定如何以其他方式进行操作。
I have an SQL Alchemy engine where I try to insert parameters via sqlalchemy.sql.text to protect against SQL injection.
The following code works, where I code variables for the condition and conditions values.
from sqlalchemy import create_engine
from sqlalchemy.sql import text
db_engine = create_engine(...)
db_engine.execute(
text(
'SELECT * FROM table_name WHERE :condition_1 = :condition_1_value'), condition_1="name", condition_1_value="John"
)
).fetchall()
However, when I try to code the variable name for table_name
, it returns an error.
from sqlalchemy import create_engine
from sqlalchemy.sql import text
db_engine = create_engine(...)
db_engine.execute(
text(
'SELECT * FROM :table_name WHERE :condition_1 = :condition_1_value'), table_name="table_1", condition_1="name", condition_1_value="John"
)
).fetchall()
Any ideas why this does not work?
EDIT:
I know that it has something to do with the table_name
not being a string, but I am not sure how to do it in another way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查询参数用于提供事物的 value (通常是列值),而不是事物的名称(表,列等)。我看过的每个数据库都这样工作。
因此,尽管无处不在的建议是动态SQL是一件“坏事”,但在某些情况下,这是必不可少的。这是其中之一。
另外,请检查您从尝试参数化列名的结果。您可能不会得到您的期望。
不会产生相当于
它的等效物将呈现等效
且不会丢失错误,但是它也不会返回行,因为
'name'='john'
永远不会是正确的。Query parameters are used to supply the values of things (usually column values), not the names of things (tables, columns, etc.). Every database I've seen works that way.
So, despite the ubiquitous advice that dynamic SQL is a "Bad Thing", there are certain cases where it is simply necessary. This is one of them.
Also, check the results you get from trying to parameterize a column name. You may not be getting what you expect.
will not produce the equivalent of
It will render the equivalent of
and will not throw an error, but it will also return no rows because
'name' = 'John'
will never be true.