python防止sql注入的方法:
1. 使用cursor.execute(sql, args)的参数位:
sql_str = "select * from py_msgcontrol.py_msgcontrol_file_base_info where file_name = %s" args = ["12';select now();"] conn = pymysql.connect(**conn_dic) cursor = conn.cursor() cursor.execute(sql_str, args)
cursor.execute函数将传入的args中的特殊符号进行了转义,从而防止了sql注入的问题。
注意点是要传入sql语句的字符串占位用引号包起来会出错,像这样:
sql_str = "select * from py_msgcontrol.py_msgcontrol_file_base_info where file_name = '%s'"
报错:
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '12\';select now();''' at line 1")
2. 使用pymysql.escape_string对参数进行转义
args = pymysql.escape_string("12';select now();") sql_str = "select * from py_msgcontrol.py_msgcontrol_file_base_info where file_name = '%s'" % args conn = pymysql.connect(**conn_dic) cursor = conn.cursor() cursor.execute(sql_str)