使用 psycopg2/Python DB-API 和 PostgreSQL 进行参数化查询 [英] Parameterized queries with psycopg2 / Python DB-API and PostgreSQL
问题描述
让 psycopg2 将参数化查询传递给 PostgreSQL 的最佳方法是什么?我不想编写自己的 escpaing 机制或适配器,而且 psycopg2 源代码和示例很难在网络浏览器中阅读.
What's the best way to make psycopg2 pass parameterized queries to PostgreSQL? I don't want to write my own escpaing mechanisms or adapters and the psycopg2 source code and examples are difficult to read in a web browser.
如果我需要切换到 PyGreSQL 或其他 python pg 适配器之类的东西,那对我来说没问题.我只想要简单的参数化.
If I need to switch to something like PyGreSQL or another python pg adapter, that's fine with me. I just want simple parameterization.
推荐答案
psycopg2
遵循 DB-API 2.0 的规则(在 PEP-249).这意味着您可以从 cursor
对象调用 execute
方法并使用 pyformat
绑定样式,它会为您进行转义.例如,以下应该是安全的(并且有效):
psycopg2
follows the rules for DB-API 2.0 (set down in PEP-249). That means you can call execute
method from your cursor
object and use the pyformat
binding style, and it will do the escaping for you. For example, the following should be safe (and work):
cursor.execute("SELECT * FROM student WHERE last_name = %(lname)s",
{"lname": "Robert'); DROP TABLE students;--"})
这篇关于使用 psycopg2/Python DB-API 和 PostgreSQL 进行参数化查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!