MySQL python操做MySQL 索引

[TOC]python

使用python 操做MySQL

先去客戶端下載安裝pymysql 模塊: pip install pymysql

import pymysql

user = input('輸入用戶名:').strip()
pwd = input('輸入密碼:').strip()

鏈接數據庫用到的參數
conn = pymysql.connect(host='localhost',  # 指定鏈接本地服務器
                       user='root',    # 登陸服務器 用的用戶名
                       password='123',  # 登陸服務器用的密碼
                       database='test',    # 指定目標數據庫
                       charset='utf8')

# cursor = conn.cursor()  # 調用conn.cursor()實例化一個對象命名爲cursor,用於操做數據庫。默認返回的值是元祖類型

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)   # 規定返回的值爲字典類型,不然默認返回元組類型

sql = "select * from user where name= %s and password= %s "  # 編輯一條指令
cursor.execute(sql,(user,pwd))   # cursor調用execute方法執行sql指令,execute會先轉譯和檢驗參數,符合規範才傳給sql。

conn.commit()

用res接收返回的數據fetchone返回一條(字典類型)數據,fetchall、fetchmany返回一個(包含多條字典數據)列表
res = cursor.fetchall()   # 取出全部的數據 返回的是列表套字典
res = cursor.fetchone()   # 取出一條數據 返回的是字典類型
res = cursor.fetchmany(12)  # 制定獲取多少條數據 返回的是列表套字典

print(res)  

cursor.close()  
conn.close()

sql注入問題

注入問題是指:經過輸入特殊字符,讓校驗代碼失效,從而經過驗證。

輸入用戶名:xxx ' or 1=1 #
		輸入密碼:xxxx
		select * from user where name='xxx' or 1=1 #' and password='xxxx'
		[{'id': 1, 'name': 'zhangsan', 'password': ''}, {'id': 2, 'name': 'zekai', 'password': '123'}, {'id': 3, 'name': 'kkk', 'password': ''}]

解決方法: 對用戶輸入的內容進行過濾和規範

sql = "select * from user where name=%s and password=%s"
		cursor.execute(sql, (user, pwd))

fetchall() : 取出全部的數據 返回的是列表套字典
		fetchone() : 取出一條數據 返回的是字典
		fetchmany(size) : 取出size條數據 返回的是列表套字典
        
 print(cursor.lastrowid)   # 獲取最後一行的ID值

增長一條數據:

sql = "insert into user (name, password) values (%s,  %s)"
cursor.execute(sql, ('frank', '111'))  ### 新增一條數據
conn.commit()

增長多條數據:

sql = "insert into user (name, password) values (%s,  %s)"
data = [
    ('allen2','1232'),
    ('allen3','1233'),
    ('allen4','1234'),
    ('allen5','1235')
]
cursor.executemany(sql, data)
conn.commit()

改:

sql = "update user set name=%s,pwd=%s where id=%s"
cursor.execute(sql, (hugo, 987, 2))
conn.commit()

刪:有外鍵的數據用這個方法刪不掉

sql = "delete from test1 where id=%s;"
cursor.execute(sql, id)
conn.commit()

索引

做用:提升查詢效率

本質:是一個特殊的文件

原理:B+樹

分類:

主鍵索引: 加速查找 + 不能重複 + 不能爲空 primary key

惟一索引: 加速查找 + 不能重複 unique(name)

聯合惟一索引:unique(name, email)

​ 例子: ​ zekai 123@qq.com ​ zekai 123@qq.cmmysql

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

聯合索引: index (name, email)

索引的建立和刪除

主鍵索引

建立主鍵索引
方法1、建立表時建立主鍵索引 寫法一:
create table biao (
	id int auto_increment primary key
)
方法2、建立表時建立主鍵索引 寫法二:
create table b (
	id int auto_increment,
    primary key(id)
)
方法3、alter table biao change id id int auto_increment primary key;
方法4、alter table biao add primary key (id);
刪除主鍵索引:
alter table biao drop primary key ;

惟一索引:

建立索引
方法1、建立表時建立索引
create table biao(
	id int auto_increment primary key,
    name varchar(32) not null default '',
    unique u_name(name)
)
方法2、 create unique index 索引名 on 表名(字段名);

​ create unique index ix_name on biao(name);sql

方法3、alter table biao add unique index ix_name(name);
刪除: alter table biao drop index u_name ;

普通索引

建立索引:
方法1、建立表時建立索引
create table t3(
	id int auto_increment primary key,
    name varchar(32) not null default '',
    index u_name(name)
)charset=utf8;
方法2、create index 索引名 on 表名 (字段名);

​ create index ix_name on biao(name);數據庫

刪除:alter table biao drop index u_name;

索引的優缺點:

優勢: 提升查詢效率

缺點: 佔用磁盤空間

不會命中索引的狀況:

​ a. 不能在SQl語句中,進行四則運算, 會下降SQL的查詢效率 ​ b. 使用函數 ​ select * from tb1 where reverse(email) = 'zekai';服務器

​ c. 類型不一致 ​ 若是列是字符串類型,傳入條件是必須用引號引發來,否則... ​ select * from tb1 where email = 999;函數

​ #排序條件爲索引,則select字段必須也是索引字段,不然沒法命中 ​ d. order by ​ select name from s1 order by email desc; ​ 當根據索引排序時候,select查詢的字段若是不是索引,則速度仍然很慢工具

​ select email from s1 order by email desc; ​ 特別的:若是對主鍵排序,則仍是速度很快: ​ select * from tb1 order by nid desc;fetch

​ e. count(1)或count(列)代替count(*)在mysql中沒有差異了 ​ f. 組合索引最左前綴 ​ 何時會建立聯合索引? ​ 根據公司的業務場景, 在最經常使用的幾列上添加索引spa

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

​ e. count(1)或count(列)代替count(*)在mysql中沒有差異了日誌

​ f. 組合索引最左前綴

​ 何時會建立聯合索引?

​ 根據公司的業務場景, 在最經常使用的幾列上添加索引

​ 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='xxxx' -- 命中索引

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

​ where email='zekai@qq.com' -- 未命中索引

​ 例子:

​ index (a,b,c,d)

​ where a=2 and b=3 and c=4 and d=5 --->命中索引

​ where a=2 and c=3 and d=4 ----> 未命中

explain:是一個SQL的執行工具,會返回一個報告

explain
			
			mysql> explain select * from user 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的相關變量

mysql> 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.28\data\DESKTOP-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;
相關文章
相關標籤/搜索