MySQL python操作MySQL 索引


目錄

使用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.cm

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

聯合索引: index (name, email)

索引的創建和刪除

主鍵索引

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

唯一索引:

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

​ create unique index ix_name on biao(name);

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

普通索引

創建索引:
方法一、創建表時創建索引
create table t3(
	id int auto_increment primary key,
    name varchar(32) not null default '',
    index u_name(name)
)charset=utf8;
方法二、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;

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

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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM