psycopg - 获取格式化的 sql 而不是执行
我有一段 Python 代码,它通过 psycopg 与 PostgreSQL 数据库交互。
所有文献都警告不要自行执行 sql 格式化,并建议让驱动程序执行此操作。例如:
cur.execute('select name, age from people where name = %s;', ('ann',) )
驱动程序然后格式化 sql 字符串。假设我不想执行任何操作,但我只想要完全格式化的 sql 字符串。 psycopg 模块中是否有获取此格式化 sql 的功能?
I have a piece of Python code, that interacts with a PostgreSQL database via psycopg.
All literature warns against doing sql formatting by oneself, and recommends letting the driver do it. E.g.:
cur.execute('select name, age from people where name = %s;', ('ann',) )
The driver then formats the sql string. Let's say I don't want to execute anything, but I just want the fully formatted sql string. Is there any functionality for getting this formatted sql in the psycopg module?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用函数 curs.mogrify():
you wold use function curs.mogrify():
在psycopg 3中有几个游标类,只有
ClientCursor
和AsyncClientCursor
有mogrify
方法。如果要使用mogrify
,则需要在connect
函数中使用cursor_factory=ClientCursor
,或者需要实例化( Async)ClientCursor
类似于:更多详细信息
In psycopg 3 there are several cursor classes, and only
ClientCursor
andAsyncClientCursor
havemogrify
method. If you want to usemogrify
, you need to either usecursor_factory=ClientCursor
in theconnect
function, or you need to instantiate(Async)ClientCursor
similar to this:Further details
编辑:看起来以下内容不太正确,psycopg 不使用 PQexecParams,但计划使用(请参阅下面的评论)。留下答案是因为它是一个有用的抽象,对于大多数参数化查询来说都是如此,但显然还不是 psycopg2。
实际上,驱动程序不会格式化字符串。您在那里使用的称为参数化查询:sql 字符串和参数完全按照您指定的方式“通过网络”发送到 postgres,postgres 解析模板字符串,然后将参数插入到解析树中。这样,参数就不必进行编码或解码,因此不会出现任何编码错误、故障或注入攻击。 OTOH,这意味着代码中没有任何一点像您正在寻找的格式化例程一样。
有关更多详细信息,请参阅 libpq 中的“PQexecParams”方法文档 - libpq 是 Postgres 的 C 级客户端接口库。
edit: it looks like the following is not quite correct, psycopg doesn't use PQexecParams, but is planning to (See my comment below). Leaving answer because it's a useful abstraction, and true for most parameterized queries, just apparently not psycopg2 just yet.
Actually, the driver doesn't format the string. What you're using there is called a parameterized query: the sql string and the parameters are sent "across the wire" to postgres exactly as you specified them, postgres parses the template string, and then inserts the parameters into the parse tree. That way the parameters never have to be encoded or decoded, so there's no chance of any encoding errors, glitches, or injection attacks. OTOH, that means at no point in the code is there anything like the formatting routine you're looking for.
For more details, see the "PQexecParams" method in the libpq documentation - libpq is Postgres's C-level client interface library.