pymysql其他操作与补充知识

内容概要

pymysql其他操作

import pymysql 

conn = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    password = '123',  支持简写passwd
    database = 'db6',  支持简写db
    charset = 'utf8',
    autocommit = True  自动确认
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

 

默认可以执行查询操作

sql = 'select * from teacher'

默认无法执行插入、修改、删除操作

sql = 'insert into userinfo(name,password) values("tony,222")'
sql = 'update userinfo set name="jasonNB" where id=1'
sql = 'delete from userinfo where id=4'

pymysql模块针对增删改 需要二次确认

affect_rows = cursor.execute(sql)  返回值
conn.commit()  二次确认 或者可以自动确认

 

pymysql获取数据操作

print(rows) # 返回值表示的是执行sql语句之后影响的数据行数
print(cursor.fetchone()) # 从结果中获取所有的数据
print(cursor.fetchone()) # 从结果中获取一条数据
print(cursor.fetchmany(2)) # 从结果中制定获取几条数据

改变光标位置的方法:
相对位置

cursor.scroll(2,'relative') # 相对当前位置左右移动 正数往右 负数往左
print(cursor.fetchone())
绝对位置
cursor.scroll(2,'absolute')  # 相对于起始位置左右移动 正数往右
   
print(cursor.fetchone())

 

 

 

 

SQL注入

import pymysql

# 1.先获取用户名和密码
username = input('username>>>:').strip()
password = input('password>>>:').strip()
# 2.链接MySQL
conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    password='123',  # 支持简写passwd
    database='db6',  # 支持简写db
    charset='utf8',
    autocommit=True  # 自动确认
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 3.拼接查询sql语句 sql = "select * from userinfo where name=%s and password=%s" print(sql) '''pymysql模块针对增删改 需要二次确认''' # affect_rows = cursor.execute(sql, (username, password)) # 如果想一次性插入多条数据 可以使用下面的方法 affect_rows = cursor.executemany(sql, [('jason', 123), ('jason1', 123), ('jason2', 321), ('jason3', 222)]) res = cursor.fetchall() if res: print(res, '登录成功') else: print('用户名或密码错误')

sql注入两个现象

现象一

只需要用户名正确即可
    select * from userinfo where name='jasonNB' -- ajsdkjaskldjklasd' and password=''

 

现象二

用户名密码都不需要也可以
    select * from userinfo where name='xxx' or 1=1 -- jkasdjaksldklsajd' and password=''

 

利用一些特殊符号和特殊语法的形式拼接出违背常理的语句

如何解决上述现象

在SQL注入中涉及到关键性的数据不要自己手动拼接,交给固定的方法拼接(方法会自动过滤掉特殊符号)

sql = "select * from userinfo where name=%s and password=%s"
"""pymysql模块针对增删改,需要二次确认"""
affect_ rows = cursor.execute(sql,(username,password))

 

用户管理

1.创建用户
    create user 用户名 identified by '密码';
     """修改密码"""
      set password for 用户名 = Password('新密码');
        set password = Password('新密码');  # 针对当前登录用户
2.重命名
    rename user 新用户名 to 旧用户名; 
3.删除用户
    drop user 用户名;
4.查看用户访问权限
    show grants for 用户名;
5.授予访问权限
    grant select on db1.* to 用户名;
  # 授予用户对db1数据库下所有表使用select权限
6.撤销权限
    revoke select on db1.* from 用户名;

"""
整个服务器
    grant all/revoke all
整个数据库
    on db.*
特定的表
    on db.t1
"""

 

事务

四大特性:ACID

 A:原子性
   一个事务是一个完整的整体 不能分割 要么同时成功要么同时失败
C:一致性
   一致性是指事务必须使数据库从一个一致性状态变换到另一个一致性状态
I:独立性
   事务与事务彼此不干扰 相互独立
D:持久性
   事务一旦被提交了,那么对数据库中的数据的改变就是永久性的    

 

create table user(
    id int primary key auto_increment,
    name char(32),
    balance int
);

insert into user(name,balance)
values
('jason',1000),
('kevin',1000),
('tony',1000);

 

修改数据之前先开启事务操作

start transaction;

修改操作

update user set balance=900 where name='jason'; #买支付100元
update user set balance=1010 where name='kevin'; #中介拿走10元
update user set balance=1090 where name='tony'; #卖家拿到90元

 

回滚到上一个状态

rollback;

确认事务没有问题

commit;   确认之后就无法再回退

视图

1.什么是视图
    视图就是通过查询得到一张虚拟表,然后保存下来,下次直接使用即可
2.为什么要用视图
    如果要频繁使用一张虚拟表,可以不用重复查询
3.如何用视图
   create view teacher2course as select * from teacher inner join course on teacher on teacher.tid = course.teacher_id;

 

视图虽然好用但是不推荐使用!!!

触发器

在满足对某张表数据的增、删、改的情况下,自动触发的功能称之为触发器

为什么要使用触发器

  触发器专门针对我们对某一张表数据增(前后)insert/删(前后)delect/改(前后)update的行为,这类行为一旦执行就会触发触发器的执行,即自动运行另外一段sql代码

语法结构

create trigger 触发器的名字 before/after insert/update/delete on 表名 for each row
begin
    sql语句
end
针对触发器的名字有一个小习惯
    tri_before_insert_t1
        触发器简写_之前或之后_操作_表名

 

案例

CREATE TABLE cmd (
    id INT PRIMARY KEY auto_increment,
    USER CHAR (32),
    priv CHAR (10),
    cmd CHAR (64),
    sub_time datetime, # 提交时间
    success enum ('yes', 'no') #0代表执行失败
);

CREATE TABLE errlog (
    id INT PRIMARY KEY auto_increment,
    err_cmd CHAR (64),
    err_time datetime
);

 

将mysql默认的结束符由;换成$$

delimiter $$

创建一个触发器

create trigger tri_after_insert_cmd after insert on cmd for each row
begin
    if NEW.success = 'no' then  # 新记录都会被MySQL封装成NEW对象
        insert into errlog(err_cmd,err_time) values(NEW.cmd,NEW.sub_time);
    end if;
end $$
delimiter ;  # 结束之后记得再改回来,不然后面结束符就都是$$了

 

往表cmd中插入记录,触发触发器,根据IF的条件决定是否插入错误日志

INSERT INTO cmd (
    USER,
    priv,
    cmd,
    sub_time,
    success
)
VALUES
    ('jason','0755','ls -l /etc',NOW(),'yes'),
    ('jason','0755','cat /etc/passwd',NOW(),'no'),
    ('jason','0755','useradd xxx',NOW(),'no'),
    ('jason','0755','ps aux',NOW(),'yes');

 

查询errlog表记录

select * from errlog;

删除触发器

drop trigger tri_after_insert_cmd;

存储过程

# 相对于python中的自定义函数
delimiter $$
create procedure p1()
begin
    select * from cmd;
end $$
delimiter ;

# 调用
call p1()

 

函数

# 相对于python中的内置方法
"ps: 可以通过help 函数名 查看帮助信息"
# 1.移除指定字符
  Trim、LTrim、RTrim

# 2.大小写转换
  Lower、Upper

# 3.获取左右起始指定个数字符
  Left、Right

# 4.返回读音相似值(对英文有效)
  Soundex

# 5.日期格式:data_format
  '''在MySQL中表示时间格式尽量采用2022-11-11形式'''

流程控制

# if条件语句
    if i = 1 THEN
        SELECT 1;
    ELSEIF i = 2 THEN
        SELECT 2;
    ELSE
        SELECT 7;
    END IF;

# while循环语句
    SET num = 0 ;
    WHILE num < 10 DO
        SELECT
            num ;
        SET num = num + 1 ;
    END WHILE ;

 

索引

索引就是一种数据结构,类似于书的目录

  意味着以后在查数据应该先找目录再找数据,而不是用翻页的方式查询数据

 

索引在MySQL中也叫做"键",是存储引擎用于快速找到记录的一种数据结构

主键   primary key
   除了可以加快查询之外还有其他的功能
唯一键 unique
   除了可以加快查询之外还有其他的功能
索引键 index key
   除了可以加快查询之外没有其他的功能
外键   foreign key
   跟索引半毛钱关系都没有 也不存在提升查询速度一说

 

索引的影响

* 在表中有大量数据的前提下,创建索引速度会很慢
* 在索引创建完毕后,对表的查询性能会大幅度提升,但是写的性能会降低

'''思考 有一张表按照name字段查询数据 速度很慢 如何解决?'''

  1.将name字段制作索引

小结论:可以简单理解按照什么字段查询慢就把什么字段制作成索引

但是不要一遇到查询慢,就把对应的字段做成索引

 

聚集索引(primary key)

  叶子结点放的一条条完整的记录

 根节点和支节点不存储真实数据,只有叶子节点存储真实数据

 

辅助索引(unique,index)

  叶子结点存放的是辅助索引字段对应的那条记录的主键的值

覆盖索引

  只在辅助索引的叶子节点中就已经找到了所有我们想要的数据
  select name from user where name='jason';

非覆盖索引

  虽然查询的时候命中了索引字段name,但是要查的是age字段,所以还需要利用主键才去查找
  select age from user where name='jason';

索引实操练习

#1. 准备表
create table s1(
id int,
name varchar(20),
gender char(6),
email varchar(50)
);

#2. 创建存储过程,实现批量插入记录
delimiter $$ #声明存储过程的结束符号为$$
create procedure auto_insert1()
BEGIN
    declare i int default 1;
    while(i<3000000)do
        insert into s1 values(i,'jason','male',concat('jason',i,'@oldboy'));
        set i=i+1;
    end while;
END$$ #$$结束
delimiter ; #重新声明分号为结束符号

#3. 查看存储过程
show create procedure auto_insert1\G 

#4. 调用存储过程
call auto_insert1();


# 表没有任何索引的情况下
select * from s1 where id=30000;
# 避免打印带来的时间损耗
select count(id) from s1 where id = 30000;
select count(id) from s1 where id = 1;

# 给id做一个主键
alter table s1 add primary key(id);  # 速度很慢

select count(id) from s1 where id = 1;  # 速度相较于未建索引之前两者差着数量级
select count(id) from s1 where name = 'jason'  # 速度仍然很慢


"""
范围问题
"""
# 并不是加了索引,以后查询的时候按照这个字段速度就一定快   
select count(id) from s1 where id > 1;  # 速度相较于id = 1慢了很多
select count(id) from s1 where id >1 and id < 3;
select count(id) from s1 where id > 1 and id < 10000;
select count(id) from s1 where id != 3;

alter table s1 drop primary key;  # 删除主键 单独再来研究name字段
select count(id) from s1 where name = 'jason';  # 又慢了

create index idx_name on s1(name);  # 给s1表的name字段创建索引
select count(id) from s1 where name = 'jason'  # 仍然很慢!!!
"""
再来看b+树的原理,数据需要区分度比较高,而我们这张表全是jason,根本无法区分
那这个树其实就建成了“一根棍子”
"""
select count(id) from s1 where name = 'xxx';  
# 这个会很快,我就是一根棍,第一个不匹配直接不需要再往下走了
select count(id) from s1 where name like 'xxx';
select count(id) from s1 where name like 'xxx%';
select count(id) from s1 where name like '%xxx';  # 慢 最左匹配特性

# 区分度低的字段不能建索引
drop index idx_name on s1;

# 给id字段建普通的索引
create index idx_id on s1(id);
select count(id) from s1 where id = 3;  # 快了
select count(id) from s1 where id*12 = 3;  # 慢了  索引的字段一定不要参与计算

drop index idx_id on s1;
select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';
# 针对上面这种连续多个and的操作,mysql会从左到右先找区分度比较高的索引字段,先将整体范围降下来再去比较其他条件
create index idx_name on s1(name);
select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';  # 并没有加速

drop index idx_name on s1;
# 给name,gender这种区分度不高的字段加上索引并不难加快查询速度

create index idx_id on s1(id);
select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';  # 快了  先通过id已经讲数据快速锁定成了一条了
select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  # 慢了  基于id查出来的数据仍然很多,然后还要去比较其他字段

drop index idx_id on s1

create index idx_email on s1(email);
select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  # 快 通过email字段一剑封喉 


"""联合索引"""
select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  
# 如果上述四个字段区分度都很高,那给谁建都能加速查询
# 给email加然而不用email字段
select count(id) from s1 where name='jason' and gender = 'male' and id > 3; 
# 给name加然而不用name字段
select count(id) from s1 where gender = 'male' and id > 3; 
# 给gender加然而不用gender字段
select count(id) from s1 where id > 3; 

# 带来的问题是所有的字段都建了索引然而都没有用到,还需要花费四次建立的时间
create index idx_all on s1(email,name,gender,id);  # 最左匹配原则,区分度高的往左放
select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  # 速度变快
View Code

 

posted @ 2021-09-12 14:03  lovewx35  阅读(110)  评论(0)    收藏  举报