# 模块:pymysql 需要下载 import pymysql conn = pymysql.connect( host = ‘127.0.0.1‘, port = 3306, user = ‘root‘, password = ‘123‘, database = ‘day38‘, #要打开那个数据库 charset = ‘utf8‘ # 编码千万不要加- 如果写成了utf-8会直接报错 ) cursor = conn.cursor(pymysql.cursors.DictCursor) # 产生一个游标对象 以字典的形式返回查询出来的数据, 键是表的字段,值是表的字段对应的信息 sql = ‘select * from teacher‘ cursor.execute(sql) # 执行传入的sql语句 # print(res) # res是执行语句返回的数据条数,没屌用 print(cursor.fetchone()) # 只获取一条数据,读表中第一行数据 print(cursor.fetchone()) # 只获取一条数据 print(cursor.fetchone()) # 只获取一条数据 cursor.scroll(2,‘absolute‘) # 控制光标移动 absolute相对于起始位置,往后移动几位,也就是前几条不读 # cursor.scroll(1,‘relative‘) # relative相对于当前位置,往后移动几位,也就是跳过几条不读 print(cursor.fetchall()) # 获取所有的数据 返回的结果是一个列表 ‘‘‘ {‘tid‘: 1, ‘tname‘: ‘张磊老师‘} {‘tid‘: 2, ‘tname‘: ‘李平老师‘} {‘tid‘: 3, ‘tname‘: ‘刘海燕老师‘} [{‘tid‘: 3, ‘tname‘: ‘刘海燕老师‘}, {‘tid‘: 4, ‘tname‘: ‘朱云海老师‘}, {‘tid‘: 5, ‘tname‘: ‘李杰老师‘}] ‘‘‘
1.sql注入: 就是利用注释等具有特殊意义的符号,来完成一些骚操作,破解mysql验证
最后那一个空格,在一条sql语句中如果遇到select * from t1 where id > 3 -- and name=‘egon‘;则--之后的条件被注释掉了 #1、sql注入之:用户存在,绕过密码 egon‘ -- 任意字符 #2、sql注入之:用户不存在,绕过用户与密码 xxx‘ or 1=1 -- 任意字符
# 原来是我们对sql进行字符串拼接 # sql="select * from userinfo where name=‘%s‘ and password=‘%s‘" %(user,pwd) # print(sql) # res=cursor.execute(sql) #改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了) sql="select * from userinfo where name=%s and password=%s" #!!!注意%s需要去掉引号,因为pymysql会自动为我们加上 res=cursor.execute(sql,[user,pwd]) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来。
import pymysql conn = pymysql.connect( host = ‘127.0.0.1‘, port = 3306, user = ‘root‘, password = ‘123‘, database = ‘day38‘, charset = ‘utf8‘, # 编码千万不要加- 如果写成了utf-8会直接报错 autocommit = True # 这个参数配置完成后 增删改操作都不需要在手动加conn.commit了 ) cursor = conn.cursor(pymysql.cursors.DictCursor) username = input(‘username>>>:‘) password = input(‘password>>>:‘) sql = "select * from user where name =%s and password = %s" print(sql) res = cursor.execute(sql,(username,password)) # 能够帮你自动过滤特殊符号 避免sql注入的问题 # execute 能够自动识别sql语句中的%s 帮你做替换 if res: print(cursor.fetchall()) else: print(‘用户名或密码错误‘) """ 后续写sql语句 不要手动拼接关键性的数据 而是让excute帮你去做拼接(将spl末尾的username,password放到cursor.execute()里面) """
import pymysql conn = pymysql.connect( host = ‘127.0.0.1‘, port = 3306, user = ‘root‘, password = ‘123‘, database = ‘day38‘, charset = ‘utf8‘, # 编码千万不要加- 如果写成了utf-8会直接报错 autocommit = True # 这个参数配置完成后 增删改操作都不需要在手动加conn.commit了 ) cursor = conn.cursor(pymysql.cursors.DictCursor) # sql = ‘insert into user(name,password) values("jerry","666")‘ # sql = ‘update user set name = "jasonhs" where id = 1‘ sql = ‘delete from user where id = 6‘ cursor.execute(sql) # conn.commit() #上面配置后这里就不需要了 """ 增删改操作 都必须加一句 conn.commit()提交操作 """
原文:https://www.cnblogs.com/xp1315458571/p/11397512.html