数据库sql防注入 python web 数据库sql注入

python web 数据库sql注入

大家都知道在数据库查询数据时,是被提示尽量少用字符串查询数据,而是用(?,?,?)的方式代替,这样就是为了防sql注入。

那什么是sql注入呢,我们下面就演示一下:

错误实例:

[html]  view plain  copy
  1. sql = '''  
  2.     SELECT  
  3.         id,username,email  
  4.     FROM  
  5.         users  
  6.     WHERE  
  7.         username="{}" and password="{}"  
  8.     '''.format(usr, pwd)  

数据库中有条数据,username = fei ,password = 1234 ,email = [email protected]

我们这里usr = fei,pwd = 1234

我们执行正确的数据,返回,如下:

[html]  view plain  copy
  1. 打开了数据库  
  2. 查询到的数据 [(1, 'fei', '[email protected]')]  

这样就查询到了需要的数据,但是我们用一条数据库不存在的数据,usr = fei11,pwd = 1234,如下:

[html]  view plain  copy
  1. 打开了数据库  
  2. 查询到的数据 []  

数据为空,因为数据库根本没有这条数据!,但是,用sql注入的话,却可以轻松查到数据

sql注入,只需要改变一句话:

[html]  view plain  copy
  1. usr = 'fei11" or "1"="1'  

我们再次查询:

[html]  view plain  copy
  1. 打开了数据库  
  2. 查询到的数据 [(1, 'fei', '[email protected]')]  

看见了吧,因为是字符串查询,所以用个 or 条件就可以轻松摆脱限制查询到数据。

现在,我们改成正确的代码:

[html]  view plain  copy
  1. usr = 'fei11" or "1"="1'  
  2.    # usr = 'fei222'  
  3.    pwd = '1234'  
  4.    sql = '''  
  5.    SELECT  
  6.        id,username,email  
  7.    FROM  
  8.        users  
  9.    WHERE  
  10.        username= ? and password= ?  
  11.    '''  
  12.    cursor = conn.execute(sql,(usr,pwd))  

usr选择错误的且有注入,然后看结果:

[html]  view plain  copy
https://blog.csdn.net/qq_37561761/article/details/79326099
  1. 打开了数据库  
  2. 查询到的数据 []  

查询到的为空,所以在数据库操作中尽量少用字符串插入,防止sql注入。

摘自:https://blog.csdn.net/qq_37561761/article/details/79326099

猜你喜欢

转载自blog.csdn.net/qq_41804164/article/details/80463515
今日推荐