Python绑定包含转义字符的字符串

时间:2013-06-12 17:17:12

标签: python mysql sql

我的代码如下:

select_query = "SELECT DISTINCT name FROM people WHERE name in (%s)"
parameters = "'"+"','".join(['\\','--','where'])+"'"
cursor.execute(select_query, parameters)
print str(cursor._executed)

我想要执行的查询是:

SELECT DISTINCT name FROM people WHERE name in ('\','--','where')

我把这个参数作为最后的手段 - 它仍然没有完全符合我的要求。 Python转义字符,打印返回:

SELECT DISTINCT name FROM people WHERE name in ('\'\\\',\'--\',\'where\'')

2 个答案:

答案 0 :(得分:0)

你能不能把它作为原始字符串输入?

r放在字符串前面;

print "SELECT DISTINCT name FROM people WHERE name in ('\','--','where')"

SELECT DISTINCT name FROM people WHERE name in ('','--','where')

r

print r"SELECT DISTINCT name FROM people WHERE name in ('\','--','where')"

SELECT DISTINCT name FROM people WHERE name in ('\','--','where')

答案 1 :(得分:0)

问题是您的parameters是一个字符串,其中包含MySQLdb将尝试逃脱的字符。

您可以自己插入查询字符串...

select_query = "SELECT DISTINCT name FROM people WHERE name in (%s)"
parameters = "'"+"','".join(['\\','--','where'])+"'"
cursor.execute(select_query % parameters)
print str(cursor._executed)

...但是这很容易受到SQL注入的攻击,并且在你的情况下不会起作用,因为它会产生......

SELECT DISTINCT name FROM people WHERE name in ('\','--','where')

...这不是一个有效的查询,你可以从SO的语法高亮中看到。

做这样的事情更安全......

parameters = ['\\','--','where']
placeholders = ','.join(['%s'] * len(parameters))
select_query = "SELECT DISTINCT name FROM people WHERE name in (%s)" % placeholders
cursor.execute(select_query, parameters)
print str(cursor._executed)

...会产生类似......

的查询
SELECT DISTINCT name FROM people WHERE name in ('\\','--','where')

......我认为这是你真正想要的。


<强>更新

  

我希望不要这样做:占位符=','。join(['%s']   * len(参数))这就是我在这里发布的原因 - 是不是有更好的解决方案?

好吧,我不确定这是否“更好”,但您可以使用MySQLdb特定的Connection.escape_string()方法,或基础_mysql模块的escape_string()功能...

>>> import _mysql
>>> select_query = "SELECT DISTINCT name FROM people WHERE name in (%s)"
>>> parameters = "'"+"','".join(map(_mysql.escape_string, ['\\','--','where']))+"'"
>>> print select_query % parameters
SELECT DISTINCT name FROM people WHERE name in ('\\','--','where')

...但PEP249中未提及Connection.escape_string(),因此您将失去跨数据库兼容性。