ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

pymysql

2021-09-12 21:01:18  阅读:184  来源: 互联网

标签:count name s1 pymysql where id select


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)

使用python操作数据库有权限要求:

  默认可以执行查询操作

  默认无法执行修改操作

  默认无法执行删除操作

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

affect_rows = cursor.execute(sql)    # 执行命令,结果显示执行,但数据不变
conn.commit()  # 二次确认 提交

因此可以在基本格式里加上自动确认

autocommit=True

其他pymysql操作

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

pymysql移动光标

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

SQL注入

pymysql登录代码

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)
# 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('用户名或密码错误')

注意:pymysql登录代码使用%插入数据时,将插入数据写在后面时会引发严重漏洞:

现象1
    只需要用户名正确即可
    select * from userinfo where name='jasonNB' -- ajsdkjaskldjklasd' and password=''
现象2
    用户名密码都不需要也可以
    select * from userinfo where name='xxx' or 1=1 -- jkasdjaksldklsajd' and password=''

利用一些特殊符号和特殊语法的形式拼接出违背常理的语句
如何解决上述现象
在SQL注入中涉及到关键性的数据不要自己手动拼接
交由固定的方法拼接(方法会自动过滤掉特殊符号)

固定方法:

sql = "select * from userinfo where name=%s and password=%s"
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.tid = course.teacher_id;
  '''视图虽然好用但是不推荐使用!!!'''

触发器

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

为何要用触发器

  触发器专门针对我们对某一张表数据增insert(前后)、删delete(前后)、改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
);

delimiter $$ # 将mysql默认的结束符由;换成$$
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

eg:客户表中有一个顾客登记的用户名为J.Lee
但如果这是输入错误真名其实叫J.Lie,可以使用soundex匹配发音类似的
where Soundex(name)=Soundex('J.Lie')

5.日期格式:date_format

(在MySQL中表示时间格式尽量采用2022-11-11形式)
CREATE TABLE blog (
  id INT PRIMARY KEY auto_increment,
  NAME CHAR (32),
  sub_time datetime
);
INSERT INTO blog (NAME, sub_time)
VALUES
  ('第1篇','2015-03-01 11:31:21'),
  ('第2篇','2015-03-11 16:31:21'),
  ('第3篇','2016-07-01 10:21:31'),
  ('第4篇','2016-07-22 09:23:21'),
  ('第5篇','2016-07-23 10:11:11'),
  ('第6篇','2016-07-25 11:21:31'),
  ('第7篇','2017-03-01 15:33:21'),
  ('第8篇','2017-03-01 17:32:21'),
  ('第9篇','2017-03-01 18:31:21');
select date_format(sub_time,'%Y-%m'),count(id) from blog group by date_format(sub_time,'%Y-%m');

1.where Date(sub_time) = '2015-03-01'
2.where Year(sub_time)=2016 AND Month(sub_time)=07;

更多日期处理相关函数

  adddate 增加一个日期
  addtime 增加一个时间
  datediff 计算两个日期差值
...

流程控制

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字段查询数据 速度很慢 如何解决?
  将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'; # 速度变快

标签:count,name,s1,pymysql,where,id,select
来源: https://www.cnblogs.com/wyhb/p/15259822.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有