1、構建MySQL服務器html
目標:mysql
本案例要求熟悉MySQL官方安裝包的使用,快速構建一臺數據庫服務器:sql
方案:數據庫
本課程將使用64位的RHEL 7操做系統,MySQL數據庫的版本是5.7.17。bootstrap
訪問http://dev.mysql.com/downloads/mysql/,找到MySQL Community Server下載頁面,平臺選擇「Red Hat Enterprise Linux 7 / Oracle Linux」,而後選擇64位的bundle整合包下載,以下圖所示。vim
注意:下載MySQL軟件時須要以Oracle網站帳戶登陸,若是沒有請根據頁面提示先註冊一個(免費) 。安全
步驟:服務器
步驟一:準備工做socket
1)卸載系統自帶的mariadb-server、mariadb軟件包(若是有的話)tcp
[root@dbsvr1 ~]# yum -y remove mariadb-server mariadb
Setting up Remove Process
No Match for argument: mariadb-server
rhel7dvd | 3.9 kB 00:00 ...
Package(s) mariadb-server available, but not installed.
No Match for argument: mariadb
Package(s) mariadb available, but not installed.
No Packages marked for removal
2)清理/etc/my.cnf配置文件
此配置文件由RHEL自帶的mariadb-libs庫提供:
[root@dbsvr1 ~]# rpm -qf /etc/my.cnf
mariadb-libs-5.5.35-3.el7.x86_64
大量的系統軟件包都須要用到mariadb-libs庫,所以不建議直接卸載此軟件包。最好是安裝新的MySQL數據庫軟件時,採用 -U 升級的方式來進行替換。
配置文件/etc/my.cnf若不須要使用,能夠直接刪除。或者保險起見,也能夠將其更名備份:
[root@dbsvr1 ~]# mv /etc/my.cnf /etc/my.cnf.old
步驟二:安裝mysql-community-client、mysql-community-server軟件包
1)釋放bundle整合包
[root@dbsvr1 ~]# cd /var/ftp/pub/
[root@dbsvr1 pub]# tar xvf mysql-5.7.17-1.el7.x86_64.rpm-bundle.tar
mysql-community-client-5.7.17-1.el7.x86_64.rpm
//MySQL 數據庫客戶端應用程序和工具
mysql-community-common-5.7.17-1.el7.x86_64.rpm
//MySQL 數據庫和客戶端庫共享文件
mysql-community-devel-5.7.17-1.el7.x86_64.rpm
//MySQL 數據庫客戶端應用程序的庫和頭文件
mysql-community-embedded-5.7.17-1.el7.x86_64.rpm
//MySQL嵌入式函數庫
mysql-community-embedded-compat-5.7.17-1.el7.x86_64.rpm
//MySQL嵌入式兼容函數庫
mysql-community-embedded-devel-5.7.17-1.el7.x86_64.rpm
//頭文件和庫文件做爲Mysql的嵌入式庫文件
mysql-community-libs-5.7.17-1.el7.x86_64.rpm
//MySQL 數據庫客戶端應用程序的共享庫
mysql-community-libs-compat-5.7.17-1.el7.x86_64.rpm
//MySQL 5.6.31 數據庫客戶端應用程序的共享兼容庫
mysql-community-minimal-debuginfo-5.7.17-1.el7.x86_64.rpm
//mysql最小安裝包的調試信息
mysql-community-server-5.7.17-1.el7.x86_64.rpm
//很是快速和可靠的 SQL 數據庫服務器
mysql-community-server-minimal-5.7.17-1.el7.x86_64.rpm
//很是快速和可靠的 SQL 數據庫服務器(最小化安裝)
mysql-community-test-5.7.17-1.el7.x86_64.rpm
//MySQL 數據庫服務器的測試套件
2)安裝MySQL數據庫
在bundle的整合包中,並非全部的rpm包都會用到,將一些重複的刪除。
安裝mysql時可能會缺乏某些依賴包,需提早單獨安裝
[root@dbsvr1 pub]#yum -y install perl-Data-Dumper perl-JSON perl-Time-HiRes
[root@dbsvr1 pub]# rpm -Uvh mysql-community-*.rpm
準備中... ################################# [100%]
正在升級/安裝...
1:mysql-community-common-5.7.17-1.e################################# [ 9%]
2:mysql-community-libs-5.7.17-1.el7################################# [ 18%]
3:mysql-community-client-5.7.17-1.e################################# [ 27%]
4:mysql-community-server-5.7.17-1.e################################# [ 36%]
5:mysql-community-devel-5.7.17-1.el################################# [ 45%]
6:mysql-community-embedded-5.7.17-1################################# [ 55%]
7:mysql-community-embedded-devel-5.################################# [ 64%]
8:mysql-community-test-5.7.17-1.el7################################# [ 73%]
9:mysql-community-libs-compat-5.7.1################################# [ 82%]
10:mysql-community-minimal-debuginfo################################# [ 91%]
正在清理/刪除...
11:mariadb-libs-1:5.5.35-3.el7 ################################# [100%]
[root@dbsvr1 pub]#systemctl start mysqld.service
安裝過程當中會嘗試作一些檢測,而後完成基本的初始化任務,期間會給出相關的提示。好比因爲MySQL 5.7對TIMESTAMP時間戳的處理不一樣於以前的版本,會給出警告和提示出解決辦法(使用 --explicit_defaults_for_timestamp選項):
2017-04-04T15:59:07.324470Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
MySQL 5.7默認採用的存儲引擎再也不是MyISAM,而是InnoDB。初始化時若相關的文件不存在,會自動建立並設置相關參數:
2017-04-04T15:59:09.075698Z 0 [Warning] InnoDB: New log files created, LSN=45790
2017-04-04T15:59:09.381634Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2017-04-04T15:59:09.579733Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: a3973917-194f-11e7-a75b-52540018542e.
2017-04-04T15:59:09.703759Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2017-04-04T15:59:09.711439Z 1 [Note] A temporary password is generated for root@localhost: ;%7SDdD)quOI
2017-04-04T15:59:29.758102Z 1 [ERROR] Failed to open the bootstrap file /tmp/install-validate-password-plugin.xqy7Ay.sql
2017-04-04T15:59:29.758122Z 1 [ERROR] 1105 Bootstrap file error, return code (0). Nearest query: 'LSE SET @sys.tmp.table_exists.SQL = CONCAT('SELECT COUNT(*) FROM `', in_db, '`.`', in_table, '`'); PREPARE stmt_select FROM @sys.tmp.table_exists.SQL; IF (NOT v_error) THEN DEALLOCATE PREPARE stmt_select; SET out_exists = 'TEMPORARY'; END IF; END IF; END;
'
2017-04-04T15:59:29.758336Z 0 [ERROR] Aborting
2017-04-04T15:59:33.078575Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-04-04T15:59:33.092082Z 0 [Note] /usr/sbin/mysqld (mysqld 5.7.17) starting as process 3326 ...
2017-04-04T15:59:33.095074Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-04-04T15:59:33.095104Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-04-04T15:59:33.095109Z 0 [Note] InnoDB: Uses event mutexes
2017-04-04T15:59:33.095112Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-04-04T15:59:33.095115Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-04-04T15:59:33.095120Z 0 [Note] InnoDB: Using Linux native AIO
2017-04-04T15:59:33.095340Z 0 [Note] InnoDB: Number of pools: 1
2017-04-04T15:59:33.095428Z 0 [Note] InnoDB: Not using CPU crc32 instructions
2017-04-04T15:59:33.096904Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-04-04T15:59:33.106888Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-04-04T15:59:33.108711Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2017-04-04T15:59:33.120189Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2017-04-04T15:59:33.454908Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2017-04-04T15:59:33.455034Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2017-04-04T15:59:34.057704Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
2017-04-04T15:59:34.058603Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2017-04-04T15:59:34.058615Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2017-04-04T15:59:34.063078Z 0 [Note] InnoDB: Waiting for purge to start
2017-04-04T15:59:34.113304Z 0 [Note] InnoDB: 5.7.17 started; log sequence number 2536157
2017-04-04T15:59:34.113841Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
2017-04-04T15:59:34.114310Z 0 [Note] Plugin 'FEDERATED' is disabled.
2017-04-04T15:59:34.118690Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
2017-04-04T15:59:34.118921Z 0 [Warning] CA certificate ca.pem is self signed.
2017-04-04T15:59:34.119582Z 0 [Note] InnoDB: Buffer pool(s) load completed at 170404 23:59:34
2017-04-04T15:59:34.237643Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
2017-04-04T15:59:34.241687Z 0 [Note] IPv6 is available.
2017-04-04T15:59:34.241727Z 0 [Note] - '::' resolves to '::';
2017-04-04T15:59:34.241753Z 0 [Note] Server socket created on IP: '::'.
2017-04-04T15:59:34.313591Z 0 [Note] Event Scheduler: Loaded 0 events
2017-04-04T15:59:34.313686Z 0 [Note] Executing 'SELECT * FROM INFORMATION_SCHEMA.TABLES;' to get a list of tables using the deprecated partition engine. You may use the startup option '--disable-partition-engine-check' to skip this check.
2017-04-04T15:59:34.313693Z 0 [Note] Beginning of list of non-natively partitioned tables
2017-04-04T15:59:34.322126Z 0 [Note] End of list of non-natively partitioned tables
2017-04-04T15:59:34.322261Z 0 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.7.17' socket: '/var/lib/mysql/mysql.sock' port: 3306 MySQL Community Server (GPL)
關於MySQL數據庫的管理員帳號root,其密碼也再也不是空,而是安裝時隨機生成一個,這種處理方式必定程度上加強了MySQl服務器的安全性。隨機生成的密碼字串能夠從保存到mysql日誌文件中找到:
[root@dbsvr1 pub]#grep 'temporary password' /var/log/mysqld.log
2017-04-04T15:59:09.711439Z 1 [Note] A temporary password is generated for root@localhost: ;%7SDdD)quOI
3)確認安裝後的服務單元文件、服務狀態
查看服務單元文件
[root@dbsvr1 pub]# ls -lh /usr/lib/systemd/system/mysqld.service
-rw-r--r--. 1 root root 1.6K 11月 29 04:30 /usr/lib/systemd/system/mysqld.service
mysql服務的自啓狀態爲enabled:
[root@dbsvr1 ~]# # systemctl is-enabled mysqld.service
enabled
步驟三:查看Mysql服務的運行狀態
服務器進程爲mysqld,監聽的默認端口爲TCP 3306:
[root@dbsvr1 pub]# netstat -antpu | grep mysql
tcp6 0 0 :::3306 :::* LISTEN 3913/mysqld
查看Mysql服務的狀態
[root@dbsvr1 pub]#systemctl is-active mysqld.service
active
[root@dbsvr1 pub]#systemctl status mysqld.service
mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled)
Active: active (running) since 日 2017-04-23 08:56:24 CST; 1s ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 13753 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS (code=exited, status=0/SUCCESS)
Process: 13732 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 13757 (mysqld)
CGroup: /system.slice/mysqld.service
└─13757 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid
數據庫的默認存放位置爲 /var/lib/mysql:
[root@dbsvr1 pub]# ls /var/lib/mysql
auto.cnf client-cert.pem ibdata1 ibtmp1 mysql.sock.lock public_key.pem sys
ca-key.pem client-key.pem ib_logfile0 mysql performance_schema server-cert.pem
ca.pem ib_buffer_pool ib_logfile1 mysql.sock private_key.pem server-key.pem
步驟四:鏈接MySQL服務器,修改密碼
查看隨機生成的root管理密碼
[root@dbsvr1 pub]#grep 'temporary password' /var/log/mysqld.log
2017-04-01T18:10:42.948679Z 1 [Note] A temporary password is generated for root@localhost: GWphBZ_g+1& //密碼爲GWphBZ_g+1&
2)使用客戶端命令mysql鏈接到MySQL服務器
提示驗證時,填入前一步得到的隨機密碼,驗證成功後便可進入「mysql> 」環境:
[root@dbsvr1 pub]# mysql -u root -p
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 14
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;
mysql>set global validate_password_length=4;
mysql> SET PASSWORD FOR 'root'@'localhost'=PASSWORD('1234567');
Query OK, 0 rows affected, 1 warning (0.00 sec)
上述操做的結果是——更改數據庫用戶root從本機訪問時的密碼,設爲1234567。
退出「mysql> 」環境,從新登陸驗證,必須採用新的密碼才能登入:
mysql> exit //退出 mysql> 環境
Bye
[root@dbsvr1 ~]# 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.
mysql> mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.07 sec)
2、 數據庫基本管理
目標:
本案例要求熟悉MySQL的鏈接及數據庫表的增刪改查等基本管理操做,主要完成如下幾個方便的操做:
使用mysql命令鏈接數據庫
練習查看/刪除/建立庫的相關操做
練習查看/刪除/建立表的相關操做,表數據參考如表-1所示內容
步驟:
步驟一:使用mysql命令鏈接數據庫
鏈接MySQL服務器時,最基本的用法是經過 -u 選項指定用戶名、-p指定密碼。密碼能夠寫在命令行(若是不寫,則出現交互,要求用戶輸入),固然基於安全考慮通常不推薦這麼作:
[root@dbsvr1 ~]# 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 選項指定遠程主機;若是端口不是3306,還能夠經過大寫的 -P 選項指定:
[root@dbsvr1 ~]# mysql -u root -p -h 127.0.0.1 -P 3306
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
鏈接其餘主機的MySQL服務,有一個前提條件——對方已經添加了此用戶今後客戶機訪問的數據庫受權,受權操做方法會在後續課程學習。
步驟二:練習查看/刪除/建立庫的相關操做
以root用戶登入「mysql> 」環境後,能夠執行各類MySQL指令、SQL指令。基本的用法事項以下:
1)查看現有的庫
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema | //信息概要庫
| mysql | //受權庫
| performance_schema | //性能結構庫
| sys | //系統元數據庫
+--------------------+
4 rows in set (0.15 sec)
2)切換/使用指定的庫
切換到sys庫:
mysql> USE sys;
Database changed
mysql> SELECT DATABASE(); //確認當前所在的庫
+------------+
| DATABASE() |
+------------+
| sys |
+------------+
1 row in set (0.00 sec)
切換到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> SELECT DATABASE(); //確認當前所在的庫
+------------+
| DATABASE() |
+------------+
| mysql |
+------------+
1 row in set (0.00 sec)
3)建立新的庫
新建名爲mydb的庫,確認結果:
mysql> CREATE DATABASE mydb;
Query OK, 1 row affected (0.00 sec)
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mydb | //新建的mydb庫
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
新建名爲newdb的庫,確認結果:
mysql> CREATE DATABASE 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)
新建數據庫之後,會爲每一個數據庫創建同名文件夾,可從命令行確認:
[root@dbsvr1 ~]# ls -l /var/lib/mysql/{my,new}db/
/var/lib/mysql/mydb/:
總用量 4
-rw-r-----. 1 mysql mysql 65 4月 2 03:14 db.opt
/var/lib/mysql/newdb/:
總用量 4
-rw-r-----. 1 mysql mysql 65 4月 2 03:15 db.opt
4)刪除指定的庫
刪除名爲newdb的庫:
mysql> DROP DATABASE newdb;
Query OK, 0 rows affected (0.04 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> DESCRIBE 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> DESCRIBE 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)
上述操做中,DESCRIBE可縮寫爲DESC;另外,當引用非當前庫中的表時,能夠用「庫名.表名」的形式。好比,切換爲mysql庫再執行「DESCRIBE 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.04 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 配置,而後重啓數據庫服務。
[root@dbsvr1 ~]# vim /etc/my.cnf //修改運行服務配置
[mysqld]
.. ..
character_set_server=utf8
[root@dbsvr1 ~]# systemctl restart mysqld //重啓服務
.. ..
[root@dbsvr1 ~]# 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 數據類型
目標:
本案例要求熟悉MySQL的字段數據類型、時間函數的使用,完成如下任務操做:
步驟:
步驟一:建立home庫、family表
1)新建home庫,並切換到home庫
mysql> CREATE DATABASE home;
Query OK, 1 row affected (0.00 sec)
mysql> USE home;
Database changed
2)新建family表
假定family表用來記錄每一個家庭成員的姓名(name)、性別(gender)、出生日期(birth)、職業(job)、與戶主關係(relation)。
mysql> CREATE TABLE family(
-> 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)
查看family表的字段結構:
mysql> DESC family;
+----------+----------------------+------+-----+---------+-------+
| 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 sec)
4、表結構的調整
目標:
本案例要求熟悉MySQL庫中表的字段修改,主要練習如下操做:
步驟:
步驟一:添加字段
在home中建立tea6表
mysql> CREATE TABLE home.tea6(id int(4) PRIMARY KEY,
-> name varchar(4) NOT NULL,
-> age int(2) NOT NULL
-> );
Query OK, 0 rows affected (0.34 sec)
爲tea6表添加一個address字段
添加前:
mysql> DESC tea6;
+-------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+-------+
| id | int(4) | NO | PRI | NULL | |
| name | varchar(4) | NO | | NULL | |
| age | int(2) | NO | | NULL | |
+-------+------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
添加address字段:
mysql> ALTER TABLE tea6 ADD address varchar(48);
Query OK, 0 rows affected (0.84 sec)
Records: 0 Duplicates: 0 Warnings: 0
添加後(默認做爲最後一個字段):
mysql> DESC tea6;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| id | int(4) | NO | PRI | NULL | |
| name | varchar(4) | NO | | NULL | |
| age | int(2) | NO | | NULL | |
| address | varchar(48) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
3)在tea6表的age列以後添加一個gender字段
添加操做:
mysql> ALTER TABLE tea6 ADD gender enum('boy','girl') AFTER age;
Query OK, 0 rows affected (0.59 sec)
Records: 0 Duplicates: 0 Warnings: 0
確認添加結果:
mysql> DESC tea6;
+---------+--------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------------+------+-----+---------+-------+
| id | int(4) | NO | PRI | NULL | |
| name | varchar(4) | NO | | NULL | |
| age | int(2) | NO | | NULL | |
| gender | enum('boy','girl') | YES | | NULL | |
| address | varchar(48) | YES | | NULL | |
+---------+--------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
步驟二:修改字段名和字段類型
將tea6表的gender字段更名爲sex,並添加非空約束
修改操做:
mysql> ALTER TABLE tea6 CHANGE gender
-> sex enum('boy','girl') NOT NULL;
Query OK, 0 rows affected (0.08 sec)
Records: 0 Duplicates: 0 Warnings: 0
確認修改結果:
mysql> DESC tea6;
+---------+--------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------------+------+-----+---------+-------+
| id | int(4) | NO | PRI | NULL | |
| name | varchar(4) | NO | | NULL | |
| age | int(2) | NO | | NULL | |
| sex | enum('boy','girl') | NO | | NULL | |
| address | varchar(48) | YES | | NULL | |
+---------+--------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
步驟三:刪除字段
刪除tea6表中名爲sex的字段:
mysql> ALTER TABLE tea6 DROP sex; //刪除操做
Query OK, 0 rows affected (0.52 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> DESC tea6; //確認刪除結果
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| id | int(4) | NO | PRI | NULL | |
| name | varchar(4) | NO | | NULL | |
| age | int(2) | NO | | NULL | |
| address | varchar(48) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
附加:
MySQL密碼強度審計插件:validate_password的使用說明
相信不少人在平常工做中,都會遇到設置用戶、密碼之類的問題,不少人使用keepass來生成和保存密碼;可是,不少人爲了易於記憶,會選擇相對簡答的密碼,這樣,在安全性方面,會存在很是嚴重的安全隱患。
在mysql 5.6對密碼的強度進行了增強,推出了validate_password 插件。支持密碼的強度要求。
此插件要求版本:5.6.6 以上版本
安裝方式:
1.安裝插件:(默認安裝了插件後,強度插件就啓用了,關閉,須要在配置文件假如相關關閉參數)
mysql>INSTALL PLUGIN validate_password SONAME 'validate_password.so';
2.配置文件添加部分參數:
[mysqld]
plugin-load=validate_password.so
validate_password_policy=2
validate-password=FORCE_PLUS_PERMANENT
3.以上處理後,就能夠測試了:
mysql> SET PASSWORD = PASSWORD('abc');
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
mysql> SET PASSWORD = '*0D3CED9BEC10A777AEC23CCC353A8C08A633045E';
Query OK, 0 rows affected (0.01 sec)
4.相關說明:
(1).相關選項:
validate-password=ON/OFF/FORCE/FORCE_PLUS_PERMANENT: 決定是否使用該插件(及強制/永久強制使用)。
validate_password_dictionary_file:插件用於驗證密碼強度的字典文件路徑。
validate_password_length:密碼最小長度。
validate_password_mixed_case_count:密碼至少要包含的小寫字母個數和大寫字母個數。
validate_password_number_count:密碼至少要包含的數字個數。
validate_password_policy:密碼強度檢查等級,0/LOW、1/MEDIUM、2/STRONG。
validate_password_special_char_count:密碼至少要包含的特殊字符數。
其中,關於validate_password_policy-密碼強度檢查等級:
0/LOW:只檢查長度。
1/MEDIUM:檢查長度、數字、大小寫、特殊字符。
2/STRONG:檢查長度、數字、大小寫、特殊字符字典文件。
(2).插件的安裝啓用:
插件對應的庫對象文件需在配置選項plugin_dir指定的目錄中。
可以使用--plugin-load=validate_password.so,在server啓動時載入插件,或者將plugin-load=validate_password.so寫入配置文件。
也能夠經過以下語句在server運行時載入插件(會註冊進mysql.plugins表)
mysql> INSTALL PLUGIN validate_password SONAME 'validate_password.so';
(3).爲阻止該插件在運行時被刪除可在配置文件中添加:
[mysqld]
plugin-load=validate_password.so
validate-password=FORCE_PLUS_PERMANENT
約束條件:not null 表示不容許空值
null(空值)、"null"(非空)、""(非空)、" "(非空)、NULL(非空)
枚舉類型:set("read","run","movie","sing") default "read,run": 這種枚舉類型值能夠多選; enum("boy","girl") default "boy":這種枚舉類型值只能單選。
數據庫初學總結:
1、安裝mysql包並起服務:
前提準備:
# yum -y remove mariadb-server mariadb //卸載系統自帶的數據庫
# rpm -qf /etc/my.cnf //清理配置文件
1> 安裝依賴包:perl-Data-Dumper、perl-JSON
# yum -y install perl-Data-Dumper perl-JSON
2> 將須要安裝的包解壓到指定位置
# mkdir /opt/Database1
# tar -xf mysql-5.7.17-1.el7.x86_64.rpm-bundle.tar -C /opt/Database1/ //將包解壓縮到指定位置
3> 命令cd進入指定包位置,刪掉不用的包
# cd /opt/Database1/
# rm -rf mysql-community-server-minimal-5.7.17-1.el7.x86_64.rpm //刪掉最小化安裝包
4> 將要用到的全部的rpm包安裝
# rpm -Uvh mysql-community-*.rpm //升級方式安裝目錄下的一系列rpm包
5> 啓動mysqld服務設置爲開機自啓動
# systemctl start mysqld
# systemctl enable mysqld
# netstat -antup|grep 3306 //查看端口狀態,是否啓動
2、基本的mysql操做
1> 更改數據庫登錄密碼
# grep 'password' /var/log/mysqld.log //能夠查看數據庫默認的密碼 7ekt7,Yif;Ws
2018-01-17T04:30:06.339970Z 1 [Note] A temporary password is generated for root@localhost: 7ekt7,Yif;Ws
# mysql -u root -p'7ekt7,Yif;Ws'
mysql> set global validate_password_policy=0;
mysql> set global validate_password_length=6;
mysql> alter user root@"localhost" identified by "123456";
mysql> quit
# vim /etc/my.cnf //修改mysql主配置文件
4 [mysqld]
5 validate_password_policy=0 //密碼強度檢查等級,0表示最低
6 validate_password_length=6 //密碼最小長度是6位,默認是8位,最低可設置爲4位
# systemctl stop mysqld.service
# systemctl start mysqld.service
或者:
# systemctl restart mysqld.service
2> 基本的操做:
# mysql -u root -p'123456' //-p後面緊跟密碼,最好加引號,引號能夠屏蔽特殊符號
mysql> show databases; //查看數據庫,命令行後面必須加分號結束
mysql> use mysql; //選擇想要的庫
mysql> select database(); //查看當前數據庫
mysql> show tables; //查看當前數據庫裏的數據表
mysql> create database db1; //建立數據庫,建立數據表前要先建立庫
mysql> create table db1.t2( //建立數據表,注意數據表裏面至少有一條目錄才行
-> name char(16),
-> home float(8,2),
-> phone tinyint(1),
-> id smallint(1),
-> country float(6,2)
-> );
mysql> drop table db1.t2; //刪掉數據表
mysql> create table stuinfo( //建立數據表頭,設置了默認值的話,後面插入內容,沒有該值會自動補充會
-> name char(16) not null,
-> age tinyint(1) unsigned not null default 20,
-> sex enum("boy","girl","other") not null default boy,
-> birthday date not null default 19900101,
-> love set("read","game","animal") not null default "read",
-> mail varchar(30) not null default "18318888868@163.com",
-> phone char(50) not null default "xiaomi",
-> phoneprice tinyint(1) not null default 100
-> );
mysql> insert into stuinfo values("tom","18","boy","19950808","game","15286822708@163.com","huawei","80");
//能夠直接插入值,默認是按照表頭對應順序日後填充,必須每項都填滿,不然報錯不匹配
mysql> insert into stuinfo(name,sex) values("jim","boy");
//也能夠插入指定值到指定字段,有些沒有設定默認值的,插入時必須指定默認值
mysql> desc stuinfo; //查看數據表stuinfo的字段
mysql> alter table stuinfo add home char(50) not null default "tianjing"; //數據表添加字段
mysql> alter table stuinfo drop home; //數據表刪除字段
mysql> alter table stuinfo rename to stu; //數據表更名字
mysql> alter table stuinfo modify love set("read","game","hiking") not null default "read,game,hiking";
//修改表字段信息,枚舉類型:set("a","b","c") 能夠多選;enum("a","b","c")只能單選。
mysql> alter table stuinfo modify sex set("boy","girl") not null default "boy";
//修改表字段信息,枚舉類型:set("a","b","c") 能夠多選;enum("a","b","c")只能單選。
mysql> alter table stuinfo modify love set('read','game','hiking') after name;
//挪動字段位置,須要挪動的字段類型信息也要跟上;
mysql> alter table student change love favourite set('read','game','hiking');
//給數據字段更名字
mysql> update stuinfo set age=22 where name="lucy"; //注意這個stuinfo表前面不用加table,加了反而語法錯誤;
mysql> delete from stuinfo where name="lucy"; //刪除數據表中的某個記錄
mysql> drop table t1; //刪掉整個數據表,這裏是用相對路徑,能夠絕對路徑
Mysql 數據庫可參看這個網站:http://www.runoob.com/mysql/mysql-tutorial.html
Mysql基本操做格式:
1> 建立數據庫&刪除數據庫
create database 庫名; //建立數據庫
drop database 庫名; //刪除數據庫
2> 建立數據表
create table 庫名.表名(
字段名 類型(寬度) 約束條件,
字段名 類型(寬度) 約束條件,
.....
);
3> 查看錶結構
desc 庫名.表名;
4> 查看錶記錄信息
select * from 庫名.表名;
5> 插入表記錄信息
insert into 庫.表 values("字符1","字符2",...,"字符n"); //這種方式向表裏插入的值要和表中全部字段一一匹配,不然報錯
insert into 庫.表(字段名1,字段名2,...,字段名n) values("字符1","字符2",...,"字符n"); //這種方式能夠向表裏指定的n個字段插入值,其餘字段值爲表格默認值
6> 更改表記錄信息
update 庫.表 set 字段名=「值「 where 約束條件;
7> 刪除表記錄信息
delete from 庫.表; //這種方式是刪除表記錄全部記錄
delete from 庫.表 where 約束條件; //這種方式刪除表記錄中特定條件的記錄
8> 修改表結構
格式:alter table 庫.表 執行動做;
添加新字段 :
add 字段名 類型(寬度);
add 字段名 類型(寬度) 約束條件;
add 字段名 類型(寬度) 約束條件 first;
add 字段名 類型(寬度) 約束條件 after 字段名;
add 字段名 類型(寬度),add 字段名 類型(寬度);
刪除已有字段 :
drop 字段名;
drop 字段名,drop 字段名;
修改字段類型: (修改的類型與字段已存儲的數據衝突,則不容許修改)
modify 字段名 類型(寬度) 約束條件;
修改字段名 :
change 源字段名 新字段名 類型(寬度) 約束條件;
修改表名:alter table 源表名 rename 新表名;