pymysql安装:pip3 install pymysql
第一个实例:连接数据库进行用户验证 |
条件:数据库中已存在一个用户表,包含用户名、密码
import pymysql user = input("username:") pwd = input("password:") # 连接数据库,只是打开数据库 db = pymysql.connect(host='localhost',
user='root',
password='123456',
database='userinfo', # 所用的数据库名
charset = 'utf-8') # host 数据库所在主机位置 cursor = db.cursor() # 游标,通过游标查询进行对数据库的操作,from 后是所用的表名 sql = "select * from user_pwd where username = '%s' and password = '%s'"%(user,pwd) # 这里是运用的是字符串替换 cursor.execute(sql) # 在数据库中通过语句查询 data = cursor.fetchone() # 查询结果运用fetchall() 把结果拿出来 cursor.close() # 关闭游标的使用 db.close() # 关闭数据库 if data: print("登陆成功") else: print("登陆失败")
在数据库操作中,字符串替换的操作方式,可能会遇见数据注入,何为数据注入?
例:当把用户名输入: uu' 1=1 --
若遇见这个情况
sql = "select * from user_pwd where username = '%s' and password = '%s'"%(user,pwd)
字符串替换后
sql = "select * from user_pwd where username = 'uu' or 1=1 --' and password = '%s'"
# (这里的-- 在数据库中表示的是注释的意思),所以 用户名username = uu,1=1 绝对成立,所以就绕过了用户验证直接验证成功!! 这就是数据注入!!
在pymysql 中 .execute() 函数对数据替换进行了相关处理,可直接用此函数进行字符替换,所以实例应写为:
import pymysql user = input("username:") pwd = input("password:") # 连接数据库,只是打开数据库 db = pymysql.connect(host='localhost', user='root',password='123456', database='userinfo') # host 数据库所在主机位置 cursor = db.cursor() # 游标 sql = "select * from user_pwd where username = %s and password = %s" cursor.execute(sql,(user,pwd)) # 这里不能是%,或者.format()的字符串替换,利用,可进行correctly转义,从而避免sql注入的发生 # cursor.execute(sql,[user,pwd]) # 另一种写法 #第三种写法 # sql = "select * from user_pwd where username = %(u)s and password = %(p)s" #cursor.execute(sql,{'u':user,'p':pwd}) data = cursor.fetchone() # 查询结果 cursor.close() db.close() if data: print("登陆成功") else: print("登陆失败")
pymysql的增删改 |
注:增删改都需要sql语句提交:conn.commit()
一、增加
1.基础版
import pymysql db = pymysql.connect(host='localhost', user='root',password='123456', database='userinfo') # host 数据库所在主机位置 cursor = db.cursor() # 游标 sql = "insert into user_pwd(username,password) values('vera', '1234')" # 其中数据库中id为自增序列,否则报错 cursor.execute(sql)
print(cursor.lastrowid) # 这里得到的是数据库中自增id的id值 db.commit() # 只要要修改表中的数据,都必须commit提交sql语句 cursor.close() db.close()
2.一级进阶版:手动输入用户名、密码
import pymysql user = input('username:') pwd = input('password:') db = pymysql.connect(host='localhost', user='root',password='123456', database='userinfo') # host 数据库所在主机位置 cursor = db.cursor() # 游标 sql = "insert into user_pwd(username,password) values(%s,%s)" cursor.execute(sql,(user,pwd)) # 手动输入用户名,密码 # 有一个返回值:受影响的行数(1行) db.commit() # 只要要修改表中的数据,都必须commit提交sql语句 cursor.close() db.close()
3.二级进阶:输入两个用户名、密码同时插入数据库(运用:cursor.executemany()函数)
import pymysql db = pymysql.connect(host='localhost', user='root',password='123456', database='userinfo') # host 数据库所在主机位置 cursor = db.cursor() # 游标 # sql = "insert into user_pwd(username,password) values(%s,%s)" # cursor.execute(sql,(user,pwd)) sql = "insert into user_pwd(username,password) values(%s,%s)" cursor.executemany(sql,[('guan_guan','22'),('you_you','33')]) # 有一个返回值:受影响的行数 print(