一、pymysql 模块安装(本文博客推荐:https://www.cnblogs.com/clschao/articles/10023248.html)
pip3 install pymysql
二、pymysql 方法介绍及其简单使用(增删改查:conn.commit( ))
#注:以下出现的cursor都表示游标
1、conn=pymysql.connect(host=,port=,user=,password=,database=,charset=) 连接mysql服务器
2、cursor=conn.cursor() 创建游标,如cmd中的 mysql> ,返回数据为元组
cursor=conn.cursor(cursor=pymysql.cursor.DictCursor) #创建游标,返回数据元素为字典
3、cursor.execute( "mysql语句") 执行mysql 语句, 参数为字符串类型的maysql语句,cursor是游标
4、cursor.fetchone( ) 获取一个数据
cursor.fetchmany(n ) 获取 n个数据
cursor.fetchall( ) 获取从游标位置到最后的所有的数据
5、cursor.scroll( n,'absolute') 绝对路径下游标往下跳过n条数据
cursor.scroll( n,'relative') 绝对路径下游标往下跳过n条数据
6、cursor.close( ) 关闭游标
conn.close( ) 关闭连接
import pymysql conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', password='123', database='day03', charset='utf8' ) #前提先启动mysql服务器 #输出数据的时候,根据游标往后取值 cursor=conn.cursor() #创建游标 mysql> mysql_cmd="select * from employee;" #命令语句str cursor.execute(mysql_cmd) #执行命令行语句 print(cursor.fetchone()) #获取一条数据 print("------------xxxx-------------") cursor.scroll(3,'relative') #相对路径游标往下跳过条数据 print(cursor.fetchall()) #获取所有数据 cursor.scroll(3,'absolute') #绝对路径游标往下跳过条数据 print(cursor.fetchone()) #获取一条数据
一、mysql注入(登陆)
数据表单userinfo:
import pymysql #与数据库建立连接:host,post,user,password,database,charset; conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', password='123', database='day04', charset='utf8' ) #输入需要匹配的元素 username=input("请输入用户名") #如:alex' password=input("请输入密码") #如:123' #建立游标 mysql> cursor=conn.cursor() #默认输出元组(( ,),( ,)...) verify="select * from userinfo where uname = '%s and pword = %s;"%(username,password) #数据类型 都是字符串char(20) print(verify) ret=cursor.execute(verify) print("影响的数据条数",ret) if ret: print("登录成功!") else: print("登录失败!!!")
cursor.close() #关闭游标
conn.close() #关闭连接
1、普通用户登陆
2、只知道账户进行登陆(bug登陆)
3、账户密码都不知,我TMD还是要登陆。(bid_bug)
总结咱们刚才说的两种sql注入的语句 #1、sql注入之:用户存在,绕过密码 chao' -- 任意字符 #2、sql注入之:用户不存在,绕过用户与密码 xxx' or 1=1 -- 任意字符
满满的bug,登陆形同虚设,解决方案提供两个;
(1):re 表达式
(2):mysql提供了数据处理机制(cursor.execute(mysl语句,[参数]))|cursor.executemany(mysl语句,[参数1,参数2...]))
仅需优化两条语句: verify="select * from userinfo where uname = %s and pword = %s;" #数据类型 都为字符串char(20) ret=cursor.execute(verify,[username,password])
import pymysql #与数据库建立连接:host,post,user,password,database,charset; conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', password='123', database='day04', charset='utf8' ) #输入需要匹配的元素 username=input("请输入用户名:") #如:alex' password=input("请输入密码:") #如:123 #建立游标 mysql> cursor=conn.cursor() #默认输出元组(( ,),( ,)...) verify="select * from userinfo where uname = %s and pword = %s;" #数据类型 都为字符串char(20) print(verify) ret=cursor.execute(verify,[username,password]) print("影响的数据条数",ret) if ret: print("登录成功!") else: print("登录失败!!!")