使用psycopg2/Python DB-API和PostgreSQL进行参数化查询 [英] Parameterized queries with psycopg2 / Python DB-API and PostgreSQL

查看:231
本文介绍了使用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的规则(在

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆