PyMySQL 模块
安装pymysql模块
# cmd命令行
pip3 insatll pymysql
# pycharm
setting=>pip=>pymysql=>insatll
用py代码连接mysql
import pymysql
# 1、创建连接
conn = pymysql.Connet(
host='127.0.0.1', # 目标mysql服务器的ip地址
port = 3306
user='root', # 目标服务器登录 账号
password='123', # 目标服务器登录 密码
database='db', # 要访问的库
charset='utf8', # 设置编码
autocommit=True # 设置数据的操作直接生效,无需conn.commit()使对数据的操作生效
)
# 2、创建游标
cursor = conn.cursor() # 此游标执行完毕返回的结果集默认以元组形式显示
# cursor = conn.cursor(pymysql.cursors.DictCursor) # 加上pymysql.cursors.DictCursor参数后就默认显示为字典形式了,参数中间的cursors末尾是加s的,别忘记
# 3、操作数据库
res = cursor.execute('select * from f1') # 将此sql语句发送到mysql执行获得结果并接收返回结果
print(res) # 这里显示的并非是宣布记录,而是记录的条数
# 这里找到的数据会被下面的查找代码作为查找的依据
# 查
# 需要用下面的代码读取记录
print(cursor.fetchone) # 根据游标位置 往后显示1条记录
print(cursor.fetchmany(3)) # 根据游标位置 往后显示3条记录
print(cursor.fetachall) # 根据游标位置 往后显示所有记录
# 上面三行代码读取的记录 来源都是上一次exeute('select * from f1)所得到的记录,既多次执行exeute('select * from 表名),但是fetchXXX只会在上一次的execute的结果中查找记录
# 游标移动(用法类似文件操作中的光标移动seek)
cursor.scroll(2,'absolute') # 绝对移动,参照开始位置,游标往后移2条记录,既第三条记录前
cursor.scroll(2,'relative') # 相对移动,参照当前位置,游标往后移2条记录
# 游标的移动默认为 相对移动,故上条代码可以直接:
cursor.scroll(2)
# 还可以向前移动光标
cursor.scroll(-2)
# 增
sql = "insert into db.f1(name,age) values (%s,%s)" # 注意单双引号的区分
res = cursor.execute(sql,'zxc',21)
# 一次插入多行记录
sql = "insert into user(username,password) values(%s,%s)"
res = cursor.excutemany(sql,[('zxc',21),('zdc',22),('wjw',23)]
# 改
sql = "update db.f1 set name='zdc' where id=1"
res = cursor.execute(sql)
# 删
sql = "delete from db.f1 where id=1"
res = cursor.execute(sql)
# 增和改 单执行excute并不会真正影响到数据,需要再执行conn.commit()才可以完成真正的增改
# conn.commit()
# 确认数据无误,commit会将数据真正修改到数据库
# 但是我们在连接时写的参数设置了自动确认修改,无需手动确认commit
cursor.close() # 关闭游标
conn.close() # 关闭连接
案例:检验用户名和密码是否正确
import pymysql
conn = pymysql.connet(
host='127.0.01.1',
port=3306,
user='root',
password='123',
database='db',
charset='utf8',
autocommit=True
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
username = input('username>>>:')
password = input('password>>>:')
sql = "celect * from userinfo where name=%s and password=%s"
res = cursor.execute(sql,username,password) # 在execute中给%s传参,不然会出现 注入 bug
if res:
print(cursor.fetchall())
else:
print('用户名或密码错误')
# SQL注入
# 千万不要手动拼接(关键数据的)查询条件!!!(******)
SQL注入问题
# 不要手动去拼接查询的sql语句
username = input(">>>:").strip()
password = input(">>>:").strip()
# 手动拼接:
sql = "select * from user where username='%s' and password='%s'"%(username,password)
cursor.execute(sql)
# 非手动拼接
'''
sql = "select * from user where username='%s' and password='%s'"
cursor.execute(sql,username,password)
'''
# 下面的代码可以利用sql中注释的特点获得访问权限
# 用户名正确
username >>>: jason' -- jjsakfjjdkjjkjs
# 用户名密码都不对的情况
username >>>: xxx' or 1=1 --asdjkdklqwjdjkjasdljad
password >>>: ''
# 千万不要手动拼接(关键数据的)查询条件!!!(******)