API和PostgreSQL进行参数化查询

API和PostgreSQL进行参数化查询

本文介绍了使用psycopg2/Python DB-API和PostgreSQL进行参数化查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使psycopg2将参数化查询传递给PostgreSQL的最佳方法是什么?我不想编写自己的保留机制或适配器,并且psycopg2源代码和示例很难在Web浏览器中阅读.

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进行参数化查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:57