防止sql注入
示例:
1 from pymysql import connect 2 3 class JD(object): 4 def __init__(self): 5 self.conn = connect(host="localhost",port=3306,user="root",password="",database="jing_dong",charset="utf8") 6 self.cs1 = self.conn.cursor() 7 8 @staticmethod 9 def print_msg(): 10 print("-------JING DONG---------") 11 print("1 查询所有数据") 12 print("2、查询所有品牌") 13 print("3、查询所有分类") 14 print("4、输入查询名称") 15 return input("请选择:") 16 17 def __del__(self): 18 self.cs1.close() 19 self.conn.close() 20 21 def exe_sql(self,sql): 22 self.cs1.execute(sql) 23 for i in self.cs1.fetchall(): 24 print(i) 25 26 def show_cate(self): 27 sql = "select name from goods_cates" 28 self.exe_sql(sql) 29 30 def show_brand(self): 31 sql = "select name from goods_brands" 32 self.exe_sql(sql) 33 34 def show_all(self): 35 sql = "select * from goods" 36 self.exe_sql(sql) 37 38 def show_info_by_name(self): 39 name = input("输入名称:") 40 sql = "select * from goods where name = '%s'" % name #注意这行,这种拼接sql语句,会导致注入风险 41 print("-------%s---------"%sql) 42 self.cs1.execute(sql) 43 for i in self.cs1.fetchall(): 44 print(i) 45 #### 上面黄色部分修改如下:
sql = "select * from goods where name=%s"
self.cs1.execute(sql,[name])
for i in self.cs1.fetchall():
print(i)
46 def run(self): 47 while True: 48 num = self.print_msg() 49 if num == "1": 50 self.show_all() 51 elif num == "2": 52 self.show_brand() 53 elif num == "3": 54 self.show_cate() 55 elif num == "4": 56 self.show_info_by_name() 57 else: 58 print("wrong input...try again....") 59 60 def main(): 61 jd = JD() 62 jd.run() 63 if __name__ == "__main__": 64 main()
代码40行:sql = "select * from goods where name = '%s'" % name
如果name是空的话,sql=select * from goods where name=''
所以这时候如果输入: ' or 1=1 or ' 会查询出goods表所有数据
sql会变成这样:sql = select * from goods where name = '' or 1=1 or '' #两个红色的''是sql的,黑色部分是插入的
在其下方是改进的防注入代码,让sql自己拼接后面的列表中的参数

浙公网安备 33010602011771号