Python: get escaped SQL string

When I have a cursor, I know I can safely execute a query as follows:

cur.execute("SELECT * FROM foo WHERE foo.bar = %s", (important_variable,))

Is there any way to just get the string safely without executing the query? For example, if important_variable is a string, like "foo 'bar' "baz" , I'd want the appropriately escaped one:

"SELECT * FROM foo WHERE foo.bar = "foo 'bar' "baz"

(or whatever the appropriate escaping is, I'm not even sure).

I'm using psycopg, and sqlobject.


查看游标的mogrify方法 - 它会在变量绑定后返回字符串,并显示它所做的任何引用

cur.mogrify("SELECT * FROM foo WHERE foo.bar = %s", ("foo 'bar' "baz",))

你没有告诉我们你使用的是什么库或数据库,但我认为你的问题在这里得到了回答:如何显式引用一个字符串值(Python DB API / Psycopg2)


SQLObject handles escaping/quoting itself, but if you want to use that functionality:

from sqlobject.converters import sqlrepr
print(sqlrepr('SELECT * FROM foo WHERE foo.bar = "foo 'bar' "baz', 'postgres'))

Result:

'SELECT * FROM foo WHERE foo.bar = "foo ''bar'' "baz'
链接地址: http://www.djcxy.com/p/42726.html

上一篇: 左边和右边的命令菜单在LWUIT形式

下一篇: Python:获取转义的SQL字符串