Python等同于mysql_real_escape_string,用于将字符串安全地放入MySQL? [英] Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL?

查看:128
本文介绍了Python等同于mysql_real_escape_string,用于将字符串安全地放入MySQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有Python等同于PHP的mysql_real_escape_string?

Is there a Python equivalent of PHP's mysql_real_escape_string?

我正尝试直接从Python向MySQL db中插入一些字符串,并不断被字符串中的引号绊倒.

I'm trying to insert some strings into a MySQL db direct from Python, and keep getting tripped up by quotes in the strings.

mysql_string = "INSERT INTO candidate (name, address) VALUES  " 
for k, v in v_dict.iteritems():
    mysql_string += " ('" + v_dict['name'] + "', '" + v_dict['address'] + "'), "
mysql_string += ";"
cursor.execute(mysql_string)

我已经尝试过re.escape(),但这会转义字符串中的每个非字母数字字符,这不是我所需要的-在这种情况下,我只需要转义单引号(一般来说,其他可能会跳出的内容) MySQL).

I've tried re.escape() but that escapes every non-alphanumeric character in the strings, which isn't what I need - I just need to escape single quotes in this instance (plus more generally anything else that might trip up MySQL).

我想可以手动执行此操作,但是在Python中有更聪明的方法吗?

Could do this manually I guess, but is there a smarter way to do it in Python?

推荐答案

如果您使用的是mysql-python,只需尝试

If you are using mysql-python, just try

MySQLdb.escape_string(SQL)

示例

>>> import MySQLdb
>>> MySQLdb.escape_string("'")
"\\'"

这篇关于Python等同于mysql_real_escape_string,用于将字符串安全地放入MySQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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