14-補充內容:MySQl創建用戶和授權
權限管理
我們知道我們的最高權限管理者是root用戶,它擁有着最高的權限操作。包括select、update、delete、update、grant等操作。那么一般情況在公司之后DBA工程師會創建一個用戶和密碼,讓你去連接數據庫的操作,並給當前的用戶設置某個操作的權限(或者所有權限)。那么這時就需要我們來簡單了解一下:
- 如何創建用戶和密碼
- 給當前的用戶授權
- 移除當前用戶的權限
如果你想創建一個新的用戶,則需要以下操作:
1.進入到mysql數據庫下
mysql> use mysql
Database changed
2.對新用戶增刪改
1.創建用戶: # 指定ip:192.118.1.1的mjj用戶登錄 create user 'mjj'@'192.118.1.1' identified by '123'; # 指定ip:192.118.1.開頭的mjj用戶登錄 create user 'mjj'@'192.118.1.%' identified by '123'; # 指定任何ip的mjj用戶登錄 create user 'mjj'@'%' identified by '123'; 2.刪除用戶 drop user '用戶名'@'IP地址'; 3.修改用戶 rename user '用戶名'@'IP地址' to '新用戶名'@'IP地址'; 4.修改密碼 set password for '用戶名'@'IP地址'=Password('新密碼');
創建用戶 CREATE USER 'user_name'@'host' IDENTIFIED BY 'password'; user_name:要創建用戶的名字。 host:表示要這個新創建的用戶允許從哪台機登陸,如果只允許從本機登陸,則 填 ‘localhost’ ,如果允許從遠程登陸,則填 ‘%’ password:新創建用戶的登陸數據庫密碼,如果沒密碼可以不寫。 例: CREATE USER ‘aaa’@‘localhost’ IDENTIFED BY ‘123456’; //表示創建的新用戶,名為aaa,這個新用戶密碼為123456,只允許本機登陸 CREATE USER 'bbb'@'%' IDENTIFED BY '123456';//表示新創建的用戶,名為bbb,這個用戶密碼為123456,可以從其他電腦遠程登陸mysql所在服務器 CREATE USER ‘ccc’@‘%’ ;//表示新創建的用戶ccc,沒有密碼,可以從其他電腦遠程登陸mysql服務器
3.對當前的用戶授權管理
#查看權限 show grants for '用戶'@'IP地址' #授權 mjj用戶僅對db1.t1文件有查詢、插入和更新的操作 grant select ,insert,update on db1.t1 to "mjj"@'%'; # 表示有所有的權限,除了grant這個命令,這個命令是root才有的。mjj用戶對db1下的t1文件有任意操作 grant all privileges on db1.t1 to "mjj"@'%'; #mjj用戶對db1數據庫中的文件執行任何操作 grant all privileges on db1.* to "mjj"@'%'; #mjj用戶對所有數據庫中文件有任何操作 grant all privileges on *.* to "mjj"@'%'; #取消權限 # 取消mjj用戶對db1的t1文件的任意操作 revoke all on db1.t1 from 'mjj'@"%"; # 取消來自遠程服務器的mjj用戶對數據庫db1的所有表的所有權限 revoke all on db1.* from 'mjj'@"%"; 取消來自遠程服務器的mjj用戶所有數據庫的所有的表的權限 revoke all privileges on *.* from 'mjj'@'%';
ps:在公司中,一般情況下是DBA工程師來做這些授權工作。給你一個用戶名和密碼,你來連接就可以了。
4.MySql備份命令行操作
# 備份:數據表結構+數據 mysqdump -u root db1 > db1.sql -p # 備份:數據表結構 mysqdump -u root -d db1 > db1.sql -p #導入現有的數據到某個數據庫 #1.先創建一個新的數據庫 create database db10; # 2.將已有的數據庫文件導入到db10數據庫中 mysql -u root db10 < db1.sql -p
15-可視化工具Navicat的使用
# PS:在生產環境中操作MySQL數據庫還是推薦使用命令行工具mysql,但在我們自己開發測試時,可以使用可視化工具Navicat,以圖形界面的形式操作MySQL數據庫
官網下載:https://www.navicat.com/en/products/navicat-for-mysql
網盤下載:https://pan.baidu.com/s/1bpo5mqj
需要掌握基本的操作
掌握: #1. 測試+鏈接數據庫 #2. 新建庫 #3. 新建表,新增字段+類型+約束 #4. 設計表:外鍵 #5. 新建查詢 #6. 備份庫/表 #注意: 批量加注釋:ctrl+?鍵 批量去注釋:ctrl+shift+?鍵
16-pymysql模塊的使用
本節重點:
- pymysql的下載和使用
- execute()之sql注入
- 增、刪、改:conn.commit()
- 查:fetchone、fetchmany、fetchall
一、pymysql的下載和使用
之前我們都是通過MySQL自帶的命令行客戶端工具mysql來操作數據庫,那如何在python程序中操作數據庫呢?這就用到了pymysql模塊,該模塊本質就是一個套接字客戶端軟件,使用前需要事先安裝。
(1)pymysql模塊的下載
pip3 install pymysql
(2)pymysql的使用
數據庫和數據都已存在
# 實現:使用Python實現用戶登錄,如果用戶存在則登錄成功(假設該用戶已在數據庫中) import pymysql user = input('請輸入用戶名:') pwd = input('請輸入密碼:') # 1.連接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='', db='db8', charset='utf8') # 2.創建游標 cursor = conn.cursor() #注意%s需要加引號 查詢 sql = "select * from userinfo where username='%s' and pwd='%s'" %(user, pwd) print(sql) # 3.執行sql語句 # cursor.execute(sql) result=cursor.execute(sql) #執行sql語句,返回sql查詢成功的記錄數目 print(result) # 關閉連接,游標和連接都要關閉 cursor.close() conn.close() if result: print('登陸成功') else: print('登錄失敗')
二、execute()之sql注入
最后那一個空格,在一條sql語句中如果遇到select * from userinfo where username='mjj' -- asadasdas' and pwd='' 則--之后的條件被注釋掉了(注意--后面還有一個空格) #1、sql注入之:用戶存在,繞過密碼 mjj' -- 任意字符 #2、sql注入之:用戶不存在,繞過用戶與密碼 xxx' or 1=1 -- 任意字符
解決方法:
# 原來是我們對sql進行字符串拼接 # sql="select * from userinfo where name='%s' and password='%s'" %(username,pwd) # print(sql) # result=cursor.execute(sql) #改寫為(execute幫我們做字符串拼接,我們無需且一定不能再為%s加引號了) sql="select * from userinfo where name=%s and password=%s" #!!!注意%s需要去掉引號,因為pymysql會自動為我們加上 result=cursor.execute(sql,[user,pwd]) #pymysql模塊自動幫我們解決sql注入的問題,只要我們按照pymysql的規矩來。
三、增、刪、改:conn.commit()
commit()方法:在數據庫里增、刪、改的時候,必須要進行提交,否則插入的數據不生效。
import pymysql username = input('請輸入用戶名:') pwd = input('請輸入密碼:') # 1.連接 conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8') # 2.創建游標 cursor = conn.cursor() # 操作 # 增 # sql = "insert into userinfo(username,pwd) values (%s,%s)" # effect_row = cursor.execute(sql,(username,pwd)) #同時插入多條數據 #cursor.executemany(sql,[('李四','110'),('王五','119')]) # print(effect_row)# # 改 # sql = "update userinfo set username = %s where id = 2" # effect_row = cursor.execute(sql,username) # print(effect_row) # 刪 sql = "delete from userinfo where id = 2" effect_row = cursor.execute(sql) print(effect_row) #一定記得commit conn.commit() # 4.關閉游標 cursor.close() # 5.關閉連接 conn.close()
四、查:fetchone、fetchmany、fetchall
fetchone():獲取下一行數據,第一次為首行; fetchall():獲取所有行數據源 fetchmany(4):獲取4行數據
查看一下表內容:
mysql> select * from userinfo; +----+----------+-----+ | id | username | pwd | +----+----------+-----+ | 1 | mjj | 123 | | 3 | 張三 | 110 | | 4 | 李四 | 119 | +----+----------+-----+ 3 rows in set (0.00 sec)
使用fetchone():
import pymysql # 1.連接 conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8') # 2.創建游標 cursor = conn.cursor() sql = 'select * from userinfo' cursor.execute(sql) # 查詢第一行的數據 row = cursor.fetchone() print(row) # (1, 'mjj', '123') # 查詢第二行數據 row = cursor.fetchone() print(row) # (3, '張三', '110') # 4.關閉游標 cursor.close() # 5.關閉連接 conn.close()
使用fetchall():
import pymysql # 1.連接 conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8') # 2.創建游標 cursor = conn.cursor() sql = 'select * from userinfo' cursor.execute(sql) # 獲取所有的數據 rows = cursor.fetchall() print(rows) # 4.關閉游標 cursor.close() # 5.關閉連接 conn.close() #運行結果 ((1, 'mjj', '123'), (3, '張三', '110'), (4, '李四', '119'))
默認情況下,我們獲取到的返回值是元組,只能看到每行的數據,卻不知道每一列代表的是什么,這個時候可以使用以下方式來返回字典,每一行的數據都會生成一個字典:
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #在實例化的時候,將屬性cursor設置為pymysql.cursors.DictCursor
在fetchone示例中,在獲取行數據的時候,可以理解開始的時候,有一個行指針指着第一行的上方,獲取一行,它就向下移動一行,所以當行指針到最后一行的時候,就不能再獲取到行的內容,所以我們可以使用如下方法來移動行指針:
cursor.scroll(1,mode='relative') # 相對當前位置移動 cursor.scroll(2,mode='absolute') # 相對絕對位置移動 第一個值為移動的行數,整數為向下移動,負數為向上移動,mode指定了是相對當前位置移動,還是相對於首行移動
# 1.Python實現用戶登錄 # 2.Mysql保存數據 import pymysql # 1.連接 conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8') # 2.創建游標 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) sql = 'select * from userinfo' cursor.execute(sql) # 查詢第一行的數據 row = cursor.fetchone() print(row) # (1, 'mjj', '123') # 查詢第二行數據 row = cursor.fetchone() # (3, '張三', '110') print(row) cursor.scroll(-1,mode='relative') #設置之后,光標相對於當前位置往前移動了一行,所以打印的結果為第二行的數據 row = cursor.fetchone() print(row) cursor.scroll(0,mode='absolute') #設置之后,光標相對於首行沒有任何變化,所以打印的結果為第一行數據 row = cursor.fetchone() print(row) # 4.關閉游標 cursor.close() # 5.關閉連接 conn.close() #結果如下 {'id': 1, 'username': 'mjj', 'pwd': '123'} {'id': 3, 'username': '張三', 'pwd': '110'} {'id': 3, 'username': '張三', 'pwd': '110'} {'id': 1, 'username': 'mjj', 'pwd': '123'}
fetchmany():
import pymysql # 1.連接 conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8') # 2.創建游標 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) sql = 'select * from userinfo' cursor.execute(sql) # 獲取2條數據 rows = cursor.fetchmany(2) print(rows) # 4.關閉游標 # rows = cursor.fetchall() # print(rows) cursor.close() # 5.關閉連接 conn.close() #結果如下: [{'id': 1, 'username': 'mjj', 'pwd': '123'}, {'id': 3, 'username': '張三', 'pwd': '110'}]
17-索引
一、索引的介紹
數據庫中專門用於幫助用戶快速查找數據的一種數據結構。類似於字典中的目錄,查找字典內容時可以根據目錄查找到數據的存放位置嗎,然后直接獲取。
二 、索引的作用
約束和加速查找
三、常見的幾種索引:
- 普通索引
- 唯一索引
- 主鍵索引
- 聯合索引(多列)
- 聯合主鍵索引
- 聯合唯一索引
- 聯合普通索引
無索引和有索引的區別以及建立索引的目的
無索引: 從前往后一條一條查詢
有索引:創建索引的本質,就是創建額外的文件(某種格式存儲,查詢的時候,先去格外的文件找,定好位置,然后再去原始表中直接查詢。但是創建索引越多,會對硬盤也是有損耗。
建立索引的目的
a.額外的文件保存特殊的數據結構
b.查詢快,但是插入更新刪除依然慢
c.創建索引之后,必須命中索引才能有效
索引的種類;
hash索引和BTree索引 (1)hash類型的索引:查詢單條快,范圍查詢慢 (2)btree類型的索引:b+樹,層數越多,數據量指數級增長(我們就用它,因為innodb默認支持它)
3.1 普通索引
作用:僅有一個加速查找
創建表+普通索引
create table userinfo( nid int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, index ix_name(name) );
普通索引;
create index 索引的名字 on 表名(列名)
刪除索引;
drop index 索引的名字 on 表名
查看索引
show index from 表名
3.2 唯一索引
唯一索引有兩個功能:加速查找和唯一約束(可含null)

create table userinfo( id int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, unique index ix_name(name) );
唯一索引
create unique index 索引名 on 表名(列名)
刪除唯一索引
drop index 索引名 on 表名;
3.3 主鍵索引
主鍵索引有兩個功能: 加速查找和唯一約束(不含null)

create table userinfo( id int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, unique index ix_name(name) ) or create table userinfo( id int not null auto_increment, name varchar(32) not null, email varchar(64) not null, primary key(nid), unique index ix_name(name) )
主鍵索引
alter table 表名 add primary key(列名);
刪除主鍵索引
alter table 表名 drop primary key;
alter table 表名 modify 列名 int, drop primary key;
3.4 組合索引
組合索引是將n個列組合成一個索引
其應用場景為:頻繁的同時使用n列來進行查詢,如:where name = 'alex' and email = 'alex@qq.com'。
聯合普通索引
create index 索引名 on 表名(列名1,列名2);
四、索引名詞
#覆蓋索引:在索引文件中直接獲取數據 例如: select name from userinfo where name = 'alex50000'; #索引合並:把多個單列索引合並成使用 例如: select * from userinfo where name = 'alex13131' and id = 13131;
六、正確使用索引的情況
數據庫表中添加索引后確實會讓查詢速度起飛,但前提必須是正確的使用索引來查詢,如果以錯誤的方式使用,則即使建立索引也會不奏效。
使用索引,我們必須知道:
(1)創建索引
(2)命中索引
(3)正確使用索引
准備:
#1. 准備表 create table userinfo( 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 userinfo values(i,concat('alex',i),'male',concat('egon',i,'@oldboy')); set i=i+1; end while; END$$ #$$結束 delimiter ; #重新聲明分號為結束符號 #3. 查看存儲過程 show create procedure auto_insert1\G #4. 調用存儲過程 call auto_insert1();
測試:
- like '%xx' select * from userinfo where name like '%al'; - 使用函數 select * from userinfo where reverse(name) = 'alex333'; - or select * from userinfo where id = 1 or email = 'alex122@oldbody'; 特別的:當or條件中有未建立索引的列才失效,以下會走索引 select * from userinfo where id = 1 or name = 'alex1222'; select * from userinfo where id = 1 or email = 'alex122@oldbody' and name = 'alex112' - 類型不一致 如果列是字符串類型,傳入條件是必須用引號引起來,不然... select * from userinfo where name = 999; - != select count(*) from userinfo where name != 'alex' 特別的:如果是主鍵,則還是會走索引 select count(*) from userinfo where id != 123 - > select * from userinfo where name > 'alex' 特別的:如果是主鍵或索引是整數類型,則還是會走索引 select * from userinfo where id > 123 select * from userinfo where num > 123 - order by select email from userinfo order by name desc; 當根據索引排序時候,選擇的映射如果不是索引,則不走索引 特別的:如果對主鍵排序,則還是走索引: select * from userinfo order by nid desc; - 組合索引最左前綴 如果組合索引為:(name,email) name and email -- 使用索引 name -- 使用索引 email -- 不使用索引
什么是最左前綴呢?
最左前綴匹配: create index ix_name_email on userinfo(name,email); select * from userinfo where name = 'alex'; select * from userinfo where name = 'alex' and email='alex@oldBody'; select * from userinfo where email='alex@oldBody'; 如果使用組合索引如上,name和email組合索引之后,查詢 (1)name和email ---使用索引 (2)name ---使用索引 (3)email ---不適用索引 對於同時搜索n個條件時,組合索引的性能好於多個單列索引
******組合索引的性能>索引合並的性能*********
七、索引的注意事項
(1)避免使用select * (2)count(1)或count(列) 代替count(*) (3)創建表時盡量使用char代替varchar (4)表的字段順序固定長度的字段優先 (5)組合索引代替多個單列索引(經常使用多個條件查詢時) (6)盡量使用短索引 (create index ix_title on tb(title(16));特殊的數據類型 text類型) (7)使用連接(join)來代替子查詢 (8)連表時注意條件類型需一致 (9)索引散列(重復少)不適用於建索引,例如:性別不合適
八、執行計划
explain + 查詢SQL - 用於顯示SQL執行信息參數,根據參考信息可以進行SQL優化
mysql> explain select * from userinfo; +----+-------------+----------+------+---------------+------+---------+------+---------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+----------+------+---------------+------+---------+------+---------+-------+ | 1 | SIMPLE | userinfo | ALL | NULL | NULL | NULL | NULL | 2973016 | NULL | +----+-------------+----------+------+---------------+------+---------+------+---------+-------+ mysql> explain select * from (select id,name from userinfo where id <20) as A; +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+ | 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 19 | NULL | | 2 | DERIVED | userinfo | range | PRIMARY | PRIMARY | 4 | NULL | 19 | Using where | +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+ 2 rows in set (0.05 sec)
參數說明:
select_type: 查詢類型 SIMPLE 簡單查詢 PRIMARY 最外層查詢 SUBQUERY 映射為子查詢 DERIVED 子查詢 UNION 聯合 UNION RESULT 使用聯合的結果 table: 正在訪問的表名 type: 查詢時的訪問方式,性能:all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const ALL 全表掃描,對於數據表從頭到尾找一遍 select * from userinfo; 特別的:如果有limit限制,則找到之后就不在繼續向下掃描 select * from userinfo where email = 'alex112@oldboy' select * from userinfo where email = 'alex112@oldboy' limit 1; 雖然上述兩個語句都會進行全表掃描,第二句使用了limit,則找到一個后就不再繼續掃描。 INDEX : 全索引掃描,對索引從頭到尾找一遍 select nid from userinfo; RANGE: 對索引列進行范圍查找 select * from userinfo where name < 'alex'; PS: between and in > >= < <= 操作 注意:!= 和 > 符號 INDEX_MERGE: 合並索引,使用多個單列索引搜索 select * from userinfo where name = 'alex' or nid in (11,22,33); REF: 根據索引查找一個或多個值 select * from userinfo where name = 'alex112'; EQ_REF: 連接時使用primary key 或 unique類型 select userinfo2.id,userinfo.name from userinfo2 left join tuserinfo on userinfo2.id = userinfo.id; CONST:常量 表最多有一個匹配行,因為僅有一行,在這行的列值可被優化器剩余部分認為是常數,const表很快,因為它們只讀取一次。 select id from userinfo where id = 2 ; SYSTEM:系統 表僅有一行(=系統表)。這是const聯接類型的一個特例。 select * from (select id from userinfo where id = 1) as A; possible_keys:可能使用的索引 key:真實使用的 key_len: MySQL中使用索引字節長度 rows: mysql估計為了找到所需的行而要讀取的行數 ------ 只是預估值 extra: 該列包含MySQL解決查詢的詳細信息 “Using index” 此值表示mysql將使用覆蓋索引,以避免訪問表。不要把覆蓋索引和index訪問類型弄混了。 “Using where” 這意味着mysql服務器將在存儲引擎檢索行后再進行過濾,許多where條件里涉及索引中的列,當(並且如果)它讀取索引時,就能被存儲引擎檢驗,因此不是所有帶where子句的查詢都會顯示“Using where”。有時“Using where”的出現就是一個暗示:查詢可受益於不同的索引。 “Using temporary” 這意味着mysql在對查詢結果排序時會使用一個臨時表。 “Using filesort” 這意味着mysql會對結果使用一個外部索引排序,而不是按索引次序從表里讀取行。mysql有兩種文件排序算法,這兩種排序方式都可以在內存或者磁盤上完成,explain不會告訴你mysql將使用哪一種文件排序,也不會告訴你排序會在內存里還是磁盤上完成。 “Range checked for each record(index map: N)” 這個意味着沒有好用的索引,新的索引將在聯接的每一行上重新估算,N是顯示在possible_keys列中索引的位圖,並且是冗余的
九、慢日志記錄
開啟慢查詢日志,可以讓MySQL記錄下查詢超過指定時間的語句,通過定位分析性能的瓶頸,才能更好的優化數據庫系統的性能。
(1) 進入MySql 查詢是否開了慢查詢 show variables like 'slow_query%'; 參數解釋: slow_query_log 慢查詢開啟狀態 OFF 未開啟 ON 為開啟 slow_query_log_file 慢查詢日志存放的位置(這個目錄需要MySQL的運行帳號的可寫權限,一般設置為MySQL的數據存放目錄) (2)查看慢查詢超時時間 show variables like 'long%'; ong_query_time 查詢超過多少秒才記錄 默認10秒 (3)開啟慢日志(1)(是否開啟慢查詢日志,1表示開啟,0表示關閉。) set global slow_query_log=1; (4)再次查看 show variables like '%slow_query_log%'; (5)開啟慢日志(2):(推薦) 在my.cnf 文件中 找到[mysqld]下面添加: slow_query_log =1 slow_query_log_file=C:\mysql-5.6.40-winx64\data\localhost-slow.log long_query_time = 1 參數說明: slow_query_log 慢查詢開啟狀態 1 為開啟 slow_query_log_file 慢查詢日志存放的位置 long_query_time 查詢超過多少秒才記錄 默認10秒 修改為1秒
十、分頁性能相關方案
先回顧一下,如何取當前表中的前10條記錄,每十條取一次.......
第1頁: select * from userinfo limit 0,10; 第2頁: select * from userinfo limit 10,10; 第3頁: select * from userinfo limit 20,10; 第4頁: select * from userinfo limit 30,10; ...... 第2000010頁 select * from userinfo limit 2000000,10; PS:會發現,越往后查詢,需要的時間約長,是因為越往后查,全文掃描查詢,會去數據表中掃描查詢。
最優的解決方案
(1)只有上一頁和下一頁 做一個記錄:記錄當前頁的最大id或最小id 下一頁: select * from userinfo where id>max_id limit 10; 上一頁: select * from userinfo where id<min_id order by id desc limit 10; (2) 中間有頁碼的情況 select * from userinfo where id in( select id from (select * from userinfo where id > pre_max_id limit (cur_max_id-pre_max_id)*10) as A order by A.id desc limit 10 );