生产环境还是推荐使用mysql命令行,但为了方便我们测试,可以使用IDE工具
在此我们推荐使用Navicat软件或pycharm来连接数据库,这样就能更详细直观地查询数据
| 掌握: |
| |
| |
| |
| |
| |
| |
| |
| |
| 批量加注释:ctrl+?键 |
| 批量去注释:ctrl+shift+?键 |
| import pymysql |
| user=input('用户名: ').strip() |
| pwd=input('密码: ').strip() |
| |
| |
| conn=pymysql.connect(host='localhost',user='root',password='123',database='egon',charset='utf8') |
| |
| cursor=conn.cursor() |
| |
| |
| |
| sql='select * from userinfo where name="%s" and password="%s"' %(user,pwd) |
| print(sql) |
| res=cursor.execute(sql) |
| print(res) |
| |
| cursor.close() |
| conn.close() |
| |
| if res: |
| print('登录成功') |
| else: |
| print('登录失败') |
注意:符号–会注释掉它之后的sql,正确的语法:–后至少有一个任意字符
根本原理:就根据程序的字符串拼接name=‘%s’,我们输入一个*xxx’ – haha\***,用我们输入的xxx加’在程序中拼接成一个判断条件name=’*xxx’ – haha*****’
最后那一个空格,在一条sql语句中如果遇到select * from t1 where id > 3 — and name=’egon’;则–之后的条件被注释掉了
#1、sql注入之:用户存在,绕过密码
egon’ — 任意字符
#2、sql注入之:用户不存在,绕过用户与密码
xxx’ or 1=1 — 任意字符
图12-4 数据库注入
解决方法:
| |
| |
| |
| |
| |
| |
| sql="select * from userinfo where name=%s and password=%s" |
| res=cursor.execute(sql,[user,pwd]) |
| import pymysql |
| |
| conn=pymysql.connect(host='localhost',user='root',password='123',database='egon') |
| |
| cursor=conn.cursor() |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| sql='insert into userinfo(name,password) values(%s,%s);' |
| res=cursor.executemany(sql,[("root","123456"),("lhf","12356"),("eee","156")]) |
| print(res) |
| |
| conn.commit() |
| cursor.close() |
| conn.close() |
| import pymysql |
| |
| conn=pymysql.connect(host='localhost',user='root',password='123',database='egon') |
| |
| cursor=conn.cursor() |
| |
| |
| sql='select * from userinfo;' |
| rows=cursor.execute(sql) |
| |
| |
| |
| res1=cursor.fetchone() |
| res2=cursor.fetchone() |
| res3=cursor.fetchone() |
| res4=cursor.fetchmany(2) |
| res5=cursor.fetchall() |
| print(res1) |
| print(res2) |
| print(res3) |
| print(res4) |
| print(res5) |
| print('%s rows in set (0.00 sec)' %rows) |
| |
| conn.commit() |
| cursor.close() |
| conn.close() |
| |
| ''' |
| (1, 'root', '123456') |
| (2, 'root', '123456') |
| (3, 'root', '123456') |
| ((4, 'root', '123456'), (5, 'root', '123456')) |
| ((6, 'root', '123456'), (7, 'lhf', '12356'), (8, 'eee', '156')) |
| rows in set (0.00 sec) |
| ''' |
| import pymysql |
| conn=pymysql.connect(host='localhost',user='root',password='123',database='egon') |
| cursor=conn.cursor() |
| |
| sql='insert into userinfo(name,password) values("xxx","123");' |
| rows=cursor.execute(sql) |
| print(cursor.lastrowid) #在插入语句后查看 |
| |
| conn.commit() |
| |
| cursor.close() |
| conn.close() |