索引

python 操作 pymysql :

​ 安装 : pip install pymysql

​ pymysql :

​ -sql 注入问题 : 安全问题

  • 产生原因 :

    用户输入特殊字符 ,没有对用户输入做校验

    import pymysql
    #连接数据库
    conn = pymysql.connect(
    	host = 'localhost',user ='root',
    	password = '155',database = 'db1',charset = 'utf-8')
    cursor = conn.cursor() # 默认返回元组类型数据
    
    user = input('enter to username: ').strip()
    pwd = input ('enter to passsword: ').strip()
    #输入sql指令 :
    sql = "from db1 where name = '%s' and password = '%s' " %(user,pwd)
    print(sql)
    
    #交互
    res = cursor.execute(sql)
    print(res)
    cursor.close()  #关闭连接
    conn.close()
    if res:
        print('login sucessful')
    else:
        print('login bad')
        
        
        
    sql 注入问题 : 
    	1.user = ' xxxx ' or 1 =1 #'    and password = yyyy
        # -- or语句总是正确的 '#' 注释后面的语句 --> 登陆成功
    
    解决方法 : 
    	sql = "from db1 where name = %s and password = %s"
        cursor.execute(sql,(user,pwd))  # execute() 中做筛选
    

    优化 :

    conn.pymysql.connect(host='localhost',user='root',password='123qwe',database='test',charset='utf8')
    #返回的值为字典
    cursor= conn.cursor(cursor = pymysql.cursors.Dictcursor)
    #输入多条数据
    DATA = [(元组1),(元组2),(元组3)...]
    res = cursor.executemany(sql,DATA)
    # 增 ,删 ,改 : conn.commit()
    sql = 'insert into user (name,pwd) values (%s,%s)'
    sal = 'delect from user where id = %s'
    sql = 'updqte user set  name = %s where id =%s'
    cursor.execute(sql, ('xxx', 'qwe'))
    conn.commit() # 提交 后输入的指令在表中记录成功
    
    #查 : cursor.fetchone , fetchmany , fetchall :
    	fetchone : 取一条数据 : 字典类型
        fetchmany(size) : 取size条数据,返回的是列表套字典
        fetchall : 取除所有数据 ,返回的是列表套字典
    
#获取插入的最后一条数据的字增id
import pymysql
conn = pymysql.connect(host ='localhost',user='root',password='123',charset=utf8)
cursor = conn.cursor(pymysql.cursors.Dictcursor)
sql = 'insert into userinfo(name,pwd) values (%s,%s)'
row = cursor.execute(sql)
print(cursor.lastrowid)   #再插入语句后查看

conn.commit()
cursor.close()
conn.close()

索引 :

作用 : 加快查询效率

类比 : 字典中的目录

索引的本质 : 一个特殊的文件

索引的底层原理: B+ 数

索引的种类 :

- 主键索引  : primary key  加快查找 + 不能重复 + 不能为空 
  • 唯一索引 : unique(参数) 加快查找 + 不能重复 【副页】
    • 联合唯一索引 : unique(name,email)
  • 普通索引 : 加速查找 index(参数)
    • 联合索引 :index (name,email)

索引的创建 :

​ 主键索引:

#增 create table db1(
	id int auto_increment,
    primary key(id)
    )charset = utf8;
    alter table db1 change old_id new_id auto_increment primary key;
    
    alter table db1 add primary key(is);
    #删 alter table db1 drop primary key;
    
    #改 : 先删 --》在添加

唯一索引:

#增 create table db2(
	id int auto_increment primary key,
    name varchar(32) not null default '',
    unique u_name(name)  # 创建u_name 字段名便与操作
    )charset=utf8
    
   	create unique index u_name on db2(name) #u_name  索引名
	alter table db2 add unique index u_name (name)
    #删 : alter table db2 drop  index u_name;
    

普通索引:

#增 create table db3(
	id int auto_increment primary key,
    name varchar(32) not null default '',
    index u_name(name)  # 创建u_name 字段名便与操作
    )charset=utf8
    
   	create  index u_name on db2(name) #u_name  索引名
	alter table db2 add  index u_name (name)
    #删 : alter table db2 drop  index u_name;

索引的优缺点 :

​ -创建一个表 :

​ %_ftm文件 : 表结构

​ %_ ibd 文件 : 数据 + 索引 【存储】

优缺点 :

  1. 索引加快了查询速度

    1. 加入索引,会占用大量的磁盘空间

不会命中索引的情况:--降低索引查询的效率

  1. 不能再sql 语句中,进行逻辑运算---降低索引查询的效率

  2. 再sql 语句中,使用函数---降低索引查询的效率

  3. 字段名的数据类型不一致 :

    eg: select * from db1 where email = 999; # email 字符串 ,则email 引号包裹

4. 排序条件为索引,则select 字段必须也是索引字段,否则无法命中

    	1. select name from s1 order by email desc;
         当根据索引排序时候,select查询的字段如果不是索引,则速度仍然很慢
 

    ```python
    select email from s1 order by email desc;
    特别的:如果对主键排序,则还是速度很快:
    select * from tb1 order by nid desc;
    ```

5. count(1)或count(列)代替count(*)在mysql中没有差别

6. 组合索引最左前缀

    	1. 根据公司的业务场景, 在最常用的几列上添加索引

    select * from user where name='zekai' and email='zekai@qq.com';

    ​			

    ```python
    错误的:
    index ix_name (name),
    index ix_email(email)
    正确的做法:
    index ix_name_email(name, email)
    
    如果组合索引为:ix_name_email (name,email) ************
    		
        where name='zekai' and email='xxxx'       -- 命中索引
    					
    	where name='zekai'                        -- 命中索引
    	where email='zekai@qq.com'                -- 未命中索引
    ```
  1. explain :

    explain select * from user where name = 'nick' and email = 'sd.com' G  : 转变数据结构
       
    	 id: 1          
         select_type: SIMPLE    
    	table: user
    	partitions: NULL
    	type: ref       索引指向 all
    	possible_keys: ix_name_email     可能用到的索引
    	key: ix_name_email     确实用到的索引
    	key_len: 214            索引长度
    	ref: const,const
    	rows: 1            扫描的长度
    	filtered: 100.00
    	Extra: Using index   使用到了索引
            
       索引覆盖:
     		select id from user where id =2000;
    

    慢查询日志:

    ​ -查看满sql 的相关变量

    show variable like '%slow%'
    +---------------------------+-----------------------------------------------+
    | Variable_name             | Value                                         |
    +---------------------------+-----------------------------------------------+
    | log_slow_admin_statements | OFF                                           |
    | log_slow_slave_statements | OFF                                           |
    | slow_launch_time          | 2                                             |
    | slow_query_log            | OFF   ### 默认关闭慢SQl查询日志, on                                          |
    | slow_query_log_file       | D:mysql-5.7.28dataDESKTOP-910UNQE-slow.log | ## 慢SQL记录的位置
    +---------------------------+-----------------------------------------------+
    show variables like '%long%';
    
    
    配置慢SQL的变量:
    				set global 变量名 = 值  
    				 
    				set global slow_query_log = on;  #开启慢SQl查询日志
    				
    				set global slow_query_log_file="D:/mysql-5.7.28/data/myslow.log"; #配置路径
    				
    				set global long_query_time=1; #设置时间
    
原文地址:https://www.cnblogs.com/shaozheng/p/11777238.html