Python:获取转义的SQL字符串 [英] Python: get escaped SQL string

查看:1757
本文介绍了Python:获取转义的SQL字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个游标,我知道我可以安全地执行查询如下:

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

只是得到字符串安全而不执行查询?例如,如果 important_variable 是一个字符串,例如foo'bar'\baz需要适当转义:

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

(或者任何适当的转义,我不确定) / p>

我正在使用psycopg和sqlobject。

解决方案

游标的mogrify方法 - 它将返回变量绑定后的字符串并显示它的任何引用

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


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.

解决方案

Look at the mogrify method for cursors -- it will return the string after variable binding and show any quoting it does

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

这篇关于Python:获取转义的SQL字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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