psycopg - 获取格式化的sql而不是执行

Eri*_*sen 17 python postgresql psycopg

我有一段Python代码,它通过psycopg与PostgreSQL数据库交互.

所有文献都警告不要自己进行sql格式化,并建议让驱动程序这样做.例如:

cur.execute('select name, age from people where name = %s;', ('ann',) )
Run Code Online (Sandbox Code Playgroud)

然后驱动程序格式化sql字符串.假设我不想执行任何操作,但我只想要完全格式化的sql字符串.是否有任何功能可以在psycopg模块中获取此格式化的sql?

Jan*_*rek 19

你使用函数curs.mogrify():

SQLstring = curs.mogrify('select name, age from people where name = %s;', ('ann',) )
Run Code Online (Sandbox Code Playgroud)

  • 请注意,psycopg的作者[声明](http://permalink.gmane.org/gmane.comp.python.db.psycopg.devel/4775)mogrify只应用于调试目的. (2认同)