zoukankan      html  css  js  c++  java
  • day36

    python操作mysql

    安装:pip install pymsql

    连接数据库的参数
    conn=pymysql.connect(host='localhost',user='root',password='123',database='test',charset='utf8')
    

    coursor = conn.cursor() 默认返回的值是元组类型

    coursor=conn.corsor(cursor=pymysql.cousors.DictCursor) 返回的值是字典类型(******)

    res=cursor.fetchall 取出所有的数据,返回的是列表套字典

    ``res=cursor.fetone` 取出一条数据,返回的是字典类型

    res=cursor.fetchmany(12) 制定获取多少条数据,返回的是列表套字典

    pymysql的sql注入
    
    因为过于相信用户输入的内容,根本没有做任何的校验
    需要加上对用户输入的值进行校验
    user = input('输入用户名:').strip()
    pwd = input('输入密码:').strip()
    
    解决方法:
    sql="select * from user where name =%s and password=%s"
    
    连接数据库的参数
    conn=pymysql.connect(host='localhost',user='root',password='123',database='test',charset='utf8')
    coursor=conn.corsor(cursor=pymysql.cousors.DictCursor) 返回的值是字典类型
    
    判断:
    if res:
    	print('登录成功')
    else:
    	print('登录失败')
        
        
    查:
    	fetchall():取出所有的数据,返回的是列表套字典
    	fetchone():取出一条数据,返回的是字典
    	fetchmany():取出size条数据 返回的是列表套字典
    	
        
    
    pymsql增加数据
    sql = "insert into user (name,password) values (%s,%s)"
    
    cursor.execute(sql,('fsfhs','fhdsafhosa')) #新增一条数据
    
    print(cursor.lastrowid)#获取最后一行的ID值
    
    #加如下代码
    conn.commit()
    
    # data = [
    #     ('zekai1', 'qwe'),
    #     ('zekai2', 'qwe1'),
    #     ('zekai3', 'qwe2'),
    #     ('zekai4', 'qwe3'),
    # ]
    cursor.executemany(sql,data)  #新增多条数据
    
    pymsql 修改数据
    
    sql = "updata 表名 set name=%s where id=%s"
    cursor.execute(sql,('hsdfs',2))
    
    pymsql 删除数据
    sql = "delete from 表名 where id=%s"
    
    pymsql 插入300w条数据
    sql = "insert into 表名 (字段名1,字段名2)values (%s , %s)"
    data = []
    for i in range(3000000):
    	info = ('zhangsan'+str(i),'zhangsan'+str(i)+'dsahfsdah')
    	data.append(info)	
    

    索引

    为啥使用索引以及索引的作用:

    ​ 使用索引就是为了提高查询的效率

    类比:

    ​ 字典中的目录

    索引的本质:

    ​ 一个特殊的文件

    索引底层的原理:

    ​ B+树

    索引的种类:

    ​ 主键索引:加速查找+不能重复+不能为空 primary key

    ​ 唯一索引:加速查找+不能重复 unique(name)

    ​ 联合唯一索引:unique(name,email)

    ​ 例子:

    ​ zekai 123@qq.com

    ​ 普通索引:加速查找 index(name)

    ​ 联合索引 : index(name,email)

    索引的创建:

    主键索引:
      新增主键索引:
    1.		create table xxx(
      		id int auto_increment,
      		primary key(id)
      	)
    2.alter table xxx change id id int auto_increment primary key;
    3.alter table xxx add primary key(id);
    
    显示索引:
      show create table t2;
      show index from table;	
      				
    删除主索引:
    更改语句:alter table t2 modify id int; #auto_increment自增和primary key主键 在一起必须更改为int后才能删除
    alter table t2 drop primary key;
    
    删除主键索引:
      alter  table xxx drop primary key;    
      
    唯一索引:
      新增
    1.create table xxx(
      id int auto_increment,
      name varchar(32) not null default '',
      unique u_name (name)
    )charset utf8;
    2.create unique index 索引名 on 表名 (字段名);
    3.alter table xxx add unique index ix_name (name)
    
    删除:
      alter table xxx drop index u_name;
    
    普通索引:
      新增:
    1.create table xxx(
      id int auto_increment,
      name varchar(32) not null default '',
      index u_name (name)
    )charset utf8;
    2.create index 索引名 on 表名 (字段名);
    3.alter table xxx add index ix_name (name)
    
    删除:
    alter table xxx drop index u_name;
    

    索引的优缺点:

    通过观察 *.ibd文件可知:

    1.索引加快了查询速度

    2.但加了索引之后,会占用大量的磁盘空间

    索引加的越多越好?

    不是

    不会命中索引的情况:

    1.不能在sql语句中,进行四则运算,会降低sql的查询效率

    2.使用函数

    select *from xxx where reverse(email)=‘zekai’;

    3.类型不一致

    如果列是字符串类型,传入条件必须用引号引起来,不然...

    select * from xxx where email =999;

    4.order by

    select name from xx order by email desc;

    当根据索引排序的时候,select查询的字段如果不是索引,则速度仍然很慢

    select email from xxx order by email desc;

    特别的:如果对主键排序,则还是速度很快

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

    6.组合索引最左前缀

    什么时候会创建联合索引?

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

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

    如果遇到上述的业务情况,错误的做法:

    index ix_name (name),

    index ix_email (email)

    正确的做法:

    index ix_name_email(name,email)

    如果组合索引为:ix_name_email (name,email)

    where name='zekai' and email ='xxx' ------->命中索引

    where name='zekai'----->命中索引

    where email=‘zekai@qq.com’---->未命中索引

    如果直接查最后一个字段会降低执行查询效率,如果间断性的查询字段,

    会降低查询效率

    7.explain(类似得到一个报表)

    explain select * from 表名 where name=‘zekai’ and email =‘zekai@qq.com’G

    *************************** 1. row ***************************
    							   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 variables 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记录的位置
    				+---------------------------+-----------------------------------------------+
    				5 rows in set, 1 warning (0.08 sec)
    				
    				mysql> show variables like '%long%';
    				+----------------------------------------------------------+-----------+
    				| Variable_name                                            | Value     |
    				+----------------------------------------------------------+-----------+
    				| long_query_time                                          | 10.000000 |
    				
    
    			
    配置慢sql的变量:
    set global 变量名= 值
    set global slow_query_log = on;
    set global slow_query_log_file = 'D:/mysql-5.7.28/data/myslow.log';
    set global long_query_time=1;
    
  • 相关阅读:
    线段树、最短路径、最小生成树、并查集、二分图匹配、最近公共祖先--C++模板
    数据结构中各种树
    你必须知道的基本位运算技巧(状压DP、搜索优化都会用到)
    memset为int型数组初始化问题
    Dev-C++添加代码格式化(format source code)工具Artistic Style
    让vs IIS Express支持本地静态Json文件
    什么是「供给侧改革」? 原标题:中央提的“供给侧改革”是啥意思?有谁能解说下吗?
    PowerDesigner用法和技巧
    php 调用 web Server(短信接口示例)
    sae相关配置
  • 原文地址:https://www.cnblogs.com/gfhh/p/11773805.html
Copyright © 2011-2022 走看看