python避免SQL注入的方法:
python中的pymysql在执行sql前,会对sql中的特殊字符进行转义,如:
def escape_string(value, mapping=None):
"""escape_string escapes *value* but not surround it with quotes.
Value should be bytes or unicode.
"""
if isinstance(value, unicode):
return _escape_unicode(value)
assert isinstance(value, (bytes, bytearray))
value = value.replace('\\', '\\\\')
value = value.replace('\0', '\\0')
value = value.replace('\n', '\\n')
value = value.replace('\r', '\\r')
value = value.replace('\032', '\\Z')
value = value.replace("'", "\\'")
value = value.replace('"', '\\"')
return value
执行sql的正确方法,不要在sql中拼接参数,字符转义只会针对参数args,例如:
# query作为sql模板,args为将要传入的参数
execute(query, args=None)