python操作MySQL
使用pycharm操作MySQL
连接MySQL
第三方模块 pymysql pip3 install pymysql import pymysql # 连接MySQL服务端 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='123', database='db8_2', charset='utf8' ) # 产生一个游标对象 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 编写SQL语句 sql = 'select * from teacher' affect_rows = cursor.execute(sql) print(affect_rows) # 获取执行结果 print(cursor.fetchall())
操作游标游标
# 拿取过数据后游标有停在拿取过数据的位置,如果数据被拿光了则会拿取一个空列表 # 拿取数据 cursor.fetchone() # 拿取数据库中一个数据 cursor.fetchall() # 拿取数据库中所有数据 cursor.fetchmany(1) # 拿取数据库中括号内指定数量的数据 # 操作游标 cursor.scroll(1, 'absolute') # 第一个参数代表移动的数量,absolute表示以数据库的第一个数据为参照物开始,向后移动一个位置 cursor.scroll(1, 'relative') # 第一个参数代表移动的数量,relative表示以数据库的上一次游标所在的位置为参照物开始,向后移动一个位置



mysql知识补充
# 事务(重要) ACID A:原子性 C:一致性 I:隔离性 D:持久性 原子性(atomicity) 一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。 一致性(consistency) 事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。 隔离性(isolation) 一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。 持久性(durability) 持久性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响 事务相关操作 start transcation; # 开启事务 诸多SQL操作 rollback # 回滚到操作之前的状态 commit # 确认事务操作 之后不能回滚 # 先介绍事务的三个关键字 再去用表实际展示效果 create table user( id int primary key auto_increment, name char(32), balance int ); insert into user(name,balance) values ('jason',1000), ('egon',1000), ('tank',1000); # 修改数据之前先开启事务操作 start transaction; # 修改操作 update user set balance=900 where name='jason'; #买支付100元 update user set balance=1010 where name='egon'; #中介拿走10元 update user set balance=1090 where name='tank'; #卖家拿到90元 # 回滚到上一个状态 rollback; # 开启事务之后,只要没有执行commit操作,数据其实都没有真正刷新到硬盘 commit; """开启事务检测操作是否完整,不完整主动回滚到上一个状态,如果完整就应该执行commit操作""" # 站在python代码的角度,应该实现的伪代码逻辑, try: update user set balance=900 where name='jason'; #买支付100元 update user set balance=1010 where name='egon'; #中介拿走10元 update user set balance=1090 where name='tank'; #卖家拿到90元 except 异常: rollback; else: commit;
SQL注入问题
问题:
①.只需要用户名也可以登录
②.不需要用户名和密码也可以登录
select * from user where name='jason' -- jhsadklsajdkla' and password=''
select * from user where name='xxx' or 1=1 -- sakjdkljakldjasl' and password=''
SQL注入的原因 是由于特殊符号的组合会产生特殊的效果
实际生活中 尤其是在注册用户名的时候 会非常明显的提示你很多特殊符号不能用
原因也是一样的
结论:设计到敏感数据部分 不要自己拼接 交给现成的方法拼接即可
import pymysql # 连接MySQL服务端 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='123', database='db8_3', charset='utf8', autocommit=True # 针对增 改 删自动二次确认 ) # 产生一个游标对象 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 编写SQL语句 username = input('username>>>:').strip() password = input('password>>>:').strip() sql = "select * from userinfo where name=%s and pwd=%s" cursor.execute(sql,(username,password)) # 将数据交给execute拼接 data = cursor.fetchall() if data: print(data) print('登录成功') else: print('用户名或密码错误')


浙公网安备 33010602011771号