mysql 案列 1
NSD DBA1 DAY01
1 構建MySQL伺服器
1.1 問題
本案例要求熟悉MySQL官方安裝包的使用,快速構建一臺資料庫伺服器:
- 安裝MySQL-server、MySQl-client軟體包
- 修改資料庫使用者root的密碼
- 確認MySQL服務程式執行、root可控
1.2 方案
本課程將使用64位的RHEL 7作業系統,MySQL資料庫的版本是5.7.17。
訪問http://dev.mysql.com/downloads/mysql/,找到MySQL Community Server下載頁面,平臺選擇“Red Hat Enterprise Linux 7/ Oracle Linux”,然後選擇64位的bundle整合包下載,如圖-1所示。
圖-1
注意:下載MySQL軟體時需要以Oracle網站賬戶登入,如果沒有請根據頁面提示先註冊一個(免費)
1.3 步驟
實現此案例需要按照如下步驟進行。
步驟一:準備工作
1)停止mariadb服務
- [[email protected] ~]# systemctl stop mariadb
2)刪除/etc/my.cnf配置檔案
此配置檔案由RHEL自帶的mariadb-libs庫提供:
[[email protected] ~]# rm -rf /etc/my.cnf
3)刪除資料
- [[email protected] ~]# rm -rf /var/lib/mysql/*
4)解除安裝軟體包(沒有會顯示未安裝軟體包)
- [[email protected] ~]# rpm -e --nodeps mariadb-server mariadb
- 警告:/var/log/mariadb/mariadb.log 已另存為/var/log/mariadb/mariadb.log.rpmsave
步驟二:安裝軟體包
1)安裝mysql時可能會缺少某些依賴包,需提前單獨安裝
- [[email protected] ~]# yum -y install perl-Data-Dumper perl-JSON perl-Time-HiRes
2)物理機傳輸解壓包給虛擬機器192.168.4.1
- [[email protected] ~]# cd 桌面
- [[email protected] 桌面]# scp mysql-5.7.17.tar 192.168.4.1:/root/ //給虛擬機器傳包
- [email protected]'s password:
- mysql-5.7.17.tar 100% 543MB 95.6MB/s 00:05
3)虛擬機器192.168.4.1解壓mysql-5.7.17.tar 整合包
- [[email protected] ~]# tar -xvf mysql-5.7.17.tar //解壓mysql整合包
- ./mysql-community-client-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-common-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-devel-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-embedded-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-embedded-compat-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-embedded-devel-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-libs-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-libs-compat-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-minimal-debuginfo-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-server-5.7.17-1.el7.x86_64.rpm
- ./mysql-community-test-5.7.17-1.el7.x86_64.rpm
步驟三:啟動MySQL資料庫服務並設定開機自啟
- [[email protected] ~]# systemctl start mysqld //啟動mysql服務
- [[email protected] ~]# systemctl enable mysqld //設定開機自啟
- [[email protected] ~]# systemctl status mysqld //檢視mysql服務狀態
- ● mysqld.service - MySQL Server
- Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
- Active: active (running) since 二 2018-08-28 10:03:24 CST; 8min ago
- Docs: man:mysqld(8)
- http://dev.mysql.com/doc/refman/en/using-systemd.html
- Main PID: 4284 (mysqld)
- CGroup: /system.slice/mysqld.service
- └─4284 /usr/sbin/mysqld --daemonize --pid-file=/var/r...
- 8月 28 10:02:56 localhost.localdomain systemd[1]: Starting MySQ...
- 8月 28 10:03:24 localhost.localdomain systemd[1]: Started MySQL...
- Hint: Some lines were ellipsized, use -l to show in full.
步驟四:連線MySQL伺服器,修改密碼
檢視隨機生成的root管理密碼
- [[email protected] ~]#grep 'temporary password' /var/log/mysqld.log
- 2017-04-01T18:10:42.948679Z 1 [Note] A temporary password is generated for [email protected]: mtoa>Av<p6Yk //隨機生成的管理密碼為mtoa>Av<p6Yk
2)使用客戶端命令mysql連線到MySQL伺服器
提示驗證時,填入前一步獲得的隨機密碼,驗證成功後即可進入“mysql> ”環境:
- [[email protected] ~]# mysql -u root -p'mtoa>Av<p6Yk'
- mysql: [Warning] Using a password on the command line interface can be insecure.
- Welcome to the MySQL monitor. Commands end with ; or \g.
- Your MySQL connection id is 11
- Server version: 5.7.17
- Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
- Oracle is a registered trademark of Oracle Corporation and/or its
- affiliates. Other names may be trademarks of their respective
- owners.
- Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
- mysql> //登入成功後,進入SQL操作環境
用該密碼登入到服務端後,必須馬上修改密碼,不然會報如下錯誤:
- mysql> show databases;
- ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
3)執行SET PASSWORD命令修改密碼
這個其實與validate_password_policy的值有關,預設為1,所以剛開始設定的密碼必須符合長度,且必須含有數字,小寫或大寫字母,特殊字元。如果我們不希望密碼設定的那麼複雜,需要修改兩個全域性引數:validate_password_policy與validate_password_length。validate_password_length預設值為8,最小值為4,如果你顯性指定validate_password_length的值小於4,儘管不會報錯,但validate_password_length的值將設為4。
可參考下列指令:
- mysql>set global validate_password_policy=0; //只驗證長度
- Query OK, 0 rows affected (0.00 sec)
- mysql>set global validate_password_length=6; //修改密碼長度,預設值是8個字元
- Query OK, 0 rows affected (0.00 sec)
- mysql> alter user user() identified by "123456"; //修改登陸密碼
- Query OK, 0 rows affected (0.00 sec)
上述操作的結果是——更改資料庫使用者root從本機訪問時的密碼,設為123456。
退出“mysql> ”環境,重新登入驗證,必須採用新的密碼才能登入:
- mysql> exit //退出 mysql> 環境
- Bye
- [[email protected] ~]# mysql -u root -p //重新登入
- Enter password: //輸入新設定的密碼
- Welcome to the MySQL monitor. Commands end with ; or \g.
- Your MySQL connection id is 15
- Server version: 5.7.17 MySQL Community Server (GPL)
- Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
- Oracle is a registered trademark of Oracle Corporation and/or its
- affiliates. Other names may be trademarks of their respective
- owners.
- Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
2 資料庫基本管理
2.1 問題
本案例要求熟悉MySQL的連線及資料庫表的增刪改查等基本管理操作,主要完成以下幾個方便的操作:
- 使用mysql命令連線資料庫
- 練習檢視/刪除/建立庫的相關操作
- 練習檢視/刪除/建立表的相關操作,表資料參考如表-1所示內容
表-1 測試用表資料
2.2 步驟
實現此案例需要按照如下步驟進行。
步驟一:使用mysql命令連線資料庫
連線MySQL伺服器時,最基本的用法是通過 -u 選項指定使用者名稱、-p指定密碼。密碼可以寫在命令列(如果不寫,則出現互動,要求使用者輸入),當然基於安全考慮一般不推薦這麼做:
- [[email protected] ~]# mysql -uroot -p123456 //緊挨著選項,不要空格
- mysql: [Warning] Using a password on the command line interface can be insecure.
- Welcome to the MySQL monitor. Commands end with ; or \g.
- Your MySQL connection id is 16
- Server version: 5.7.17 MySQL Community Server (GPL)
- Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
- Oracle is a registered trademark of Oracle Corporation and/or its
- affiliates. Other names may be trademarks of their respective
- owners.
- Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
- mysql> exit //退出已登入的mysql> 環境
- Bye
預設情況下,msyql命令會連線本機的MySQL服務。但在需要的時候,可以通過 -h 選項指定遠端主機;
- [[email protected] ~]# mysql -h 127.0.0.1 –u root –p
- Enter password:
- Welcome to the MySQL monitor. Commands end with ; or \g.
- Your MySQL connection id is 17
- Server version: 5.7.17 MySQL Community Server (GPL)
- Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
- Oracle is a registered trademark of Oracle Corporation and/or its
- affiliates. Other names may be trademarks of their respective
- owners.
- Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
- mysql> exit //退出已登入的mysql環境
- Bye
步驟二:練習檢視/刪除/建立庫的相關操作
以root使用者登入“mysql> ”環境後,可以執行各種MySQL指令、SQL指令。基本的用法事項如下:
- 操作指令不區分大小寫(庫名/表名、密碼、變數值等除外)。
- 每條SQL指令以 ; 結束或分隔。
- 不支援 Tab 鍵自動補齊。
- \c 可廢棄當前編寫錯的操作指令。
1)檢視現有的庫
- mysql> show databases; //檢視現有的庫
- +--------------------+
- | Database |
- +--------------------+
- | information_schema | //資訊概要庫
- | mysql | //授權庫
- | performance_schema | //效能結構庫
- | sys | //系統元資料庫
- +--------------------+
- 4 rows in set (0.15 sec)
2)切換/使用指定的庫
- mysql> use sys; //切換到sys庫
- Database changed
- mysql> select database(); //確認當前所在的庫
- +------------+
- | DATABASE() |
- +------------+
- | sys |
- +------------+
- 1 row in set (0.00 sec)
切換到mysql庫:
- mysql> use mysql; //切換到mysql庫
- Reading table information for completion of table and column names
- You can turn off this feature to get a quicker startup with -A
- Database changed
- mysql> select database(); //確認當前所在的庫
- +------------+
- | DATABASE() |
- +------------+
- | mysql |
- +------------+
- 1 row in set (0.00 sec)
- 5 rows in set (0.00 sec)
3)新建名為newdb的庫,確認結果:
- mysql> create database newdb; //新建名為newdb的庫
- Query OK, 1 row affected (0.00 sec)
- mysql> show databases;
- +--------------------+
- | Database |
- +--------------------+
- | information_schema |
- | mydb | //新建的mydb庫
- | mysql |
- | newdb | //新建的newdb庫
- | performance_schema |
- | sys |
- +--------------------+
- 6 rows in set (0.00 sec)
4)刪除指定的庫
- mysql> drop database newdb; //刪除名為newdb的庫
- Query OK, 0 rows affected (0.01 sec)
- mysql> show databases; //確認刪除結果,已無newdb庫
- +--------------------+
- | Database |
- +--------------------+
- | information_schema |
- | mydb |
- | mysql |
- | performance_schema |
- | sys |
- +--------------------+
- 5 rows in set (0.00 sec)
步驟三:練習檢視/刪除/建立表的相關操作
1)檢視指定的庫裡有哪些表
檢視mysql庫裡有哪些表:
- mysql> use mysql;
- Reading table information for completion of table and column names
- You can turn off this feature to get a quicker startup with -A
- Database changed
- mysql> show tables;
- +---------------------------+
- | Tables_in_mysql |
- +---------------------------+
- | columns_priv |
- | db |
- | engine_cost |
- | event |
- | func |
- | general_log |
- | gtid_executed |
- | help_category |
- | help_keyword |
- | help_relation |
- | help_topic |
- | innodb_index_stats |
- | innodb_table_stats |
- | ndb_binlog_index |
- | plugin |
- | proc |
- | procs_priv |
- | proxies_priv |
- | server_cost |
- | servers |
- | slave_master_info |
- | slave_relay_log_info |
- | slave_worker_info |
- | slow_log |
- | tables_priv |
- | time_zone |
- | time_zone_leap_second |
- | time_zone_name |
- | time_zone_transition |
- | time_zone_transition_type |
- | user | //存放資料庫使用者的表
- +---------------------------+
- 31 rows in set (0.00 sec)
2)檢視指定表的欄位結構
當前庫為mysql,檢視columns_priv表的結構,以列表形式展現:
- mysql> desc columns_priv\G //查看錶結構,以列表形式展現,末尾不用分號
- *************************** 1. row ***************************
- Field: Host
- Type: char(60)
- Null: NO
- Key: PRI
- Default:
- Extra:
- *************************** 2. row ***************************
- Field: Db
- Type: char(64)
- Null: NO
- Key: PRI
- Default:
- Extra:
- *************************** 3. row ***************************
- Field: User
- Type: char(32)
- Null: NO
- Key: PRI
- Default:
- Extra:
- *************************** 4. row ***************************
- Field: Table_name
- Type: char(64)
- Null: NO
- Key: PRI
- Default:
- Extra:
- *************************** 5. row ***************************
- Field: Column_name
- Type: char(64)
- Null: NO
- Key: PRI
- Default:
- Extra:
- *************************** 6. row ***************************
- Field: Timestamp
- Type: timestamp
- Null: NO
- Key:
- Default: CURRENT_TIMESTAMP
- Extra: on update CURRENT_TIMESTAMP
- *************************** 7. row ***************************
- Field: Column_priv
- Type: set('Select','Insert','Update','References')
- Null: NO
- Key:
- Default:
- Extra:
- 7 rows in set (0.01 sec)
檢視columns_priv表的結構,以表格形式展現:
- mysql> desc columns_priv; //查看錶結構,以表格形式展現末尾需要有分號
- +-------------+----------------------------------------------+------+-----+-------------------+-----------------------------+
- | Field | Type | Null | Key | Default | Extra |
- +-------------+----------------------------------------------+------+-----+-------------------+-----------------------------+
- | Host | char(60) | NO | PRI | | |
- | Db | char(64) | NO | PRI | | |
- | User | char(32) | NO | PRI | | |
- | Table_name | char(64) | NO | PRI | | |
- | Column_name | char(64) | NO | PRI | | |
- | Timestamp | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
- | Column_priv | set('Select','Insert','Update','References') | NO | | | |
- +-------------+----------------------------------------------+------+-----+-------------------+-----------------------------+
- 7 rows in set (0.00 sec)
上述操作中,當引用非當前庫中的表時,可以用“庫名.表名”的形式。比如,切換為mysql庫再執行“desc columns_priv;”,與以下操作的效果是相同的:
- mysql> desc mysql.columns_priv;
- +-------------+----------------------------------------------+------+-----+-------------------+-----------------------------+
- | Field | Type | Null | Key | Default | Extra |
- +-------------+----------------------------------------------+------+-----+-------------------+-----------------------------+
- | Host | char(60) | NO | PRI | | |
- | Db | char(64) | NO | PRI | | |
- | User | char(16) | NO | PRI | | |
- | Table_name | char(64) | NO | PRI | | |
- | Column_name | char(64) | NO | PRI | | |
- | Timestamp | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
- | Column_priv | set('Select','Insert','Update','References') | NO | | | |
- +-------------+----------------------------------------------+------+-----+-------------------+-----------------------------+
- 7 rows in set (0.00 sec)
3)在test庫中建立一個名為pwlist的表
包括name、password兩列,其中name列作為主鍵。兩個欄位值均不允許為空,其中密碼列賦予預設空值,相關操作如下所述。
切換到mydb庫:
- mysql> use mydb;
- Database changed
新建pwlist表:
- mysql> create table pwlist(
- -> name char(16) not null,
- -> password char(48)default '',
- -> primary key(name)
- -> );
- Query OK, 0 rows affected (0.38 sec)
確認新建立的表:
- mysql> show tables;
- +----------------+
- | Tables_in_mydb |
- +----------------+
- | pwlist | //新建的pwlist表
- +----------------+
- 1 rows in set (0.01 sec)
檢視pwlist表的欄位結構:
- mysql> desc pwlist;
- +----------+----------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +----------+----------+------+-----+---------+-------+
- | name | char(16) | NO | PRI | NULL | |
- | password | char(48) | YES | | | |
- +----------+----------+------+-----+---------+-------+
- 2 rows in set (0.01 sec)
4)刪除指定的表
刪除當前庫中的pwlist表:
- mysql> drop table pwlist;
- Query OK, 0 rows affected (0.01 sec)
確認刪除結果:
- mysql> show tables;
- Empty set (0.00 sec)
5)在mydb庫中建立一個學員表
表格結構及資料內容如表-1所示。
在MySQL表記憶體儲中文資料時,需要更改字符集(預設為latin1不支援中文),以便MySQL支援儲存中文資料記錄;比如,可以在建立庫或表的時候,手動新增“DEFAULT CHARSET=utf8”來更改字符集。
根據上述表格結構,建立支援中文的student表:
- mysql> CREATE TABLE mydb.student(
- -> 學號 char(9) NOT NULL,
- -> 姓名 varchar(4) NOT NULL,
- -> 性別 enum('男','女') NOT NULL,
- -> 手機號 char(11) DEFAULT '',
- -> 通訊地址 varchar(64),
- -> PRIMARY KEY(學號)
- -> ) DEFAULT CHARSET=utf8; //手工指定字符集,採用utf8
- Query OK, 0 rows affected (0.31sec)
檢視student表的欄位結構:
- mysql> DESC mydb.student;
- +--------------+-------------------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +--------------+-------------------+------+-----+---------+-------+
- | 學號 | char(9) | NO | PRI | NULL | |
- | 姓名 | varchar(4) | NO | | NULL | |
- | 性別 | enum('男','女') | NO | | NULL | |
- | 手機號 | char(11) | YES | | | |
- | 通訊地址 | varchar(64) | YES | | NULL | |
- +--------------+-------------------+------+-----+---------+-------+
- 5 rows in set (0.00 sec)
檢視student表的實際建立指令:
- mysql> SHOW CREATE TABLE mydb.student;
- +---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
- |Table |Create Table |
- +---------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
- | student | CREATE TABLE `student` (
- `學號` char(9) NOT NULL,
- `姓名` varchar(4) NOT NULL,
- `性別` enum('男','女') NOT NULL,
- `手機號` char(11) DEFAULT '',
- `通訊地址` varchar(64) DEFAULT NULL,
- PRIMARY KEY (`學號`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
- +---------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
- 1 row in set (0.00 sec)
注意:若要修改MySQL服務的預設字符集,可以更改伺服器的my.cnf配置檔案,新增character_set_server=utf8 配置,然後重啟資料庫服務。
- [[email protected] ~]# vim /etc/my.cnf //修改執行服務配置
- [mysqld]
- .. ..
- character_set_server=utf8
- [[email protected] ~]# systemctl restart mysqld //重啟服務
- .. ..
- [[email protected] ~]# mysql –u root -p
- Enter password:
- .. ..
- mysql> SHOW VARIABLES LIKE 'character%'; //確認更改結果
- +--------------------------+----------------------------+
- | Variable_name | Value |
- +--------------------------+----------------------------+
- | character_set_client | utf8 |
- | character_set_connection | utf8 |
- | character_set_database | utf8 |
- | character_set_filesystem | binary |
- | character_set_results | utf8 |
- | character_set_server | utf8 |
- | character_set_system | utf8 |
- | character_sets_dir | /usr/share/mysql/charsets/ |
- +--------------------------+----------------------------+
- 8 rows in set (0.03 sec)
3 MySQL 資料型別
3.1 問題
- 本案例要求熟悉MySQL的欄位資料型別、表結構,各種時間函式的使用的使用,完成以下任務操作:
- 在studb庫裡建立stuinfo表,表結構、欄位型別自定義
- 表結構自定義,併合理使用資料型別
- 練習各種時間函式的使用
3.2 步驟
實現此案例需要按照如下步驟進行。
步驟一:建立studb庫、stuinfo表
1)新建studb庫,並切換到studb庫
- mysql> CREATE DATABASE studb;
- Query OK, 1 row affected (0.00 sec)
- mysql> USE studb;
- Database changed
2)新建stuinfo表
假定stuinfo表用來記錄每個家庭成員的姓名(name)、性別(gender)、出生日期(birth)、職業(job)、與戶主關係(relation)。
- mysql> CREATE TABLE stuinfo (
- -> name varchar(16) NOT NULL,
- -> gender enum('male','femal') DEFAULT 'male',
- -> birth date NOT NULL,
- -> job varchar(16) DEFAULT '',
- -> relation varchar(24) NOT NULL,
- -> PRIMARY KEY(name)
- -> );
- Query OK, 0 rows affected (0.61sec)
檢視stuinfo表的欄位結構:
- mysql> DESC stuinfo;
- +----------+----------------------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +----------+----------------------+------+-----+---------+-------+
- | name | varchar(16) | NO | PRI | NULL | |
- | gender | enum('male','femal') | YES | | male | |
- | birth | date | NO | | NULL | |
- | job | varchar(16) | YES | | | |
- | relation | varchar(24) | NO | | NULL | |
- +----------+----------------------+------+-----+---------+-------+
- 5 rows in set (0.00 sec)
步驟二:練習各種時間函式的使用
1)使用now()檢視當前的日期和時間
- mysql> SELECT now();
- +---------------------+
- | now() |
- +---------------------+
- | 2017-04-02 04:02:42 |
- +---------------------+
- 1 row in set (0.00 sec)
2)使用sysdate()檢視系統日期和時間
- mysql> SELECT sysdate();
- +---------------------+
- | sysdate() |
- +---------------------+
- | 2017-04-02 04:03:21 |
- +---------------------+
- 1 row in set (0.00 sec)
3)使用curdate()獲得當前的日期,不含時間
- mysql> SELECT curdate();
- +------------+
- | curdate() |
- +------------+
- | 2017-04-02 |
- +------------+
- 1 row in set (0.00 sec)
4)使用curtime()獲得當前的時間,不含日期
- mysql> SELECT curtime();
- +-----------+
- | curtime() |
- +-----------+
- | 04:04:55 |
- +-----------+
- 1 row in set (0.00 sec)
5)分別獲取當前日期時間中的年份、月份、日
- mysql> SELECT year(now()),month(now()),day(now());
- +-------------+--------------+------------+
- | year(now()) | month(now()) | day(now()) |
- +-------------+--------------+------------+
- | 2017 | 4 | 2 |
- +-------------+--------------+------------+
- 1 row in set (0.00 sec)
6)獲取系統日期時間中的月份、日
- mysql> SELECT month(sysdate()),day(sysdate());
- +------------------+----------------+
- | month(sysdate()) | day(sysdate()) |
- +------------------+----------------+
- | 4 | 2 |
- +------------------+----------------+
- 1 row in set (0.00 sec)
7)獲取系統日期時間中的時刻
- mysql> SELECT time(sysdate());
- +-----------------+
- | time(sysdate()) |
- +-----------------+
- | 04:06:08 |
- +-----------------+
- 1 row in set (0.00