1. 程式人生 > >2.MySQL用戶管理,常用SQL語句,MySQL數據庫備份與恢復

2.MySQL用戶管理,常用SQL語句,MySQL數據庫備份與恢復

MySQL用戶管理 常用MySQL語句 MySQL數據備份與恢復

[toc]

MySQL用戶管理,重用SQL語句,MySQL數據庫備份與恢復

一、MySQL用戶管理

1.創建一個普通用戶並授權

首先啟動mysql,然後進入

[root@xavi ~]# /etc/init.d/mysqld start
Starting MySQL... SUCCESS! 
[root@xavi ~]# mysql -uroot -pxavilinux
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 1
Server version: 5.6.35 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> 

all表示所有的權限(如讀、寫、查詢、刪除等操作);創建user用戶並授予其所有權限.(第一個表示所有數據庫,第二個表示所有表)這裏的user1特指localhost上的user1,用戶和主機的IP之間有一個@符號
br/>這裏的user1特指localhost上的user1,用戶和主機的IP之間有一個@符號

mysql>  grant all on *.* to ‘user1‘@‘127.0.0.1‘ identified by ‘123456‘; 
Query OK, 0 rows affected (0.00 sec)

另外,命令中主機IP可以用%替代,表示所有主機

mysql>  grant all on *.* to ‘user2‘@‘%‘ identified by ‘123456a‘; 
Query OK, 0 rows affected (0.00 sec)

1.1 退出,驗證user1是否可以直接登入,因為默認是socket的登入模式,無法登入

mysql> quit
Bye
[root@xavi ~]# mysql -uuser1 -p123456
Warning: Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user ‘user1‘@‘localhost‘ (using password: YES)

1.2 加上主機ip: mysql -uuser1 -p123456 -h127.0.0.1

[root@xavi ~]# mysql -uuser1 -p123456 -h127.0.0.1
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 3
Server version: 5.6.35 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> 

不加-h的方法把127.0.0.1換成localhost(針對的就是socket,localhost就是虛擬機IP地址192.168.72.130),mysql輸入出錯時,輸入;後接著輸quit退出

mysql> grant all on *.* to ‘user1‘@‘localhost‘ identified by ‘123456‘;
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye
[root@xavi ~]# mysql -uuser1 -p123456 
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 5
Server version: 5.6.35 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 grants  //查看當前用戶授權
    -> ;
+-----------------------------------------------------------------------------------------------------------------------+
| Grants for user1@localhost                                                                                            |
+-----------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO ‘user1‘@‘localhost‘ IDENTIFIED BY PASSWORD ‘*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9‘ |
+-----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

查看指定用戶授權:show grants for user1@‘127.0.0.1‘;

mysql> show grants for user1@‘127.0.0.1‘;
+-----------------------------------------------------------------------------------------------------------------------+
| Grants for [email protected]                                                                                            |
+-----------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO ‘user1‘@‘127.0.0.1‘ IDENTIFIED BY PASSWORD ‘*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9‘ |
+-----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

授權部分權限(如讀、寫、查詢、插入等)

這一部分開始操作是一只報錯

mysql> grant all on db2.* to ‘user2‘@‘192.168.188.129‘ identified by ‘111222‘;
ERROR 1044 (42000): Access denied for user ‘user1‘@‘localhost‘ to database ‘db2‘
mysql> grant all on db1.* to ‘user3‘@‘%‘ identified by ‘passwd‘;
ERROR 1044 (42000): Access denied for user ‘user1‘@‘localhost‘ to database ‘db1‘
mysql> grant all on db1.* to ‘user3‘@‘%‘ identified by ‘passwd‘;
ERROR 1044 (42000): Access denied for user ‘user1‘@‘localhost‘ to database ‘db1‘
mysql> revoke all on *.* from user1@localhost;
ERROR 1045 (28000): Access denied for user ‘user1‘@‘localhost‘ (using password: YES)
mysql> revoke all on *.* from ‘user1‘@‘localhost‘ identified by ‘123456‘; 
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘‘123456‘‘ at line 1
mysql> revoke all on *.* from ‘user1‘@‘localhost‘ identified by ‘123456‘;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘‘123456‘‘ at line 1
mysql> show grants for user1@‘127.0.0.1‘;

錯誤的原因是自己一直是在user1的數據庫可裏操作,之前的步驟中進入了“mysql -uuser1 -p123456”這就是陷阱了

正確操作方法是,進入mysql的root用戶下操作

mysql> quit
Bye
[root@xavi ~]# mysql -uroot -pxavilinux
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 2
Server version: 5.6.35 MySQL Community Server (GPL)

授權部分權限(如讀、寫、查詢、插入等)

mysql> grant SELECT,UPDATE,INSERT on db1.* to ‘user2‘@‘192.168.133.1‘ identified by ‘passwd‘;
Query OK, 0 rows affected (0.00 sec)

給不同IP做同一個用戶的授權,同一密碼

mysql> show grants for user2@‘192.168.133.1‘;
+------------------------------------------------------------------------------------------------------------------+
| Grants for [email protected]                                                                                   |
+------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO ‘user2‘@‘192.168.133.1‘ IDENTIFIED BY PASSWORD ‘*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0‘ |
| GRANT SELECT, INSERT, UPDATE ON `db1`.* TO ‘user2‘@‘192.168.133.1‘                                               |
+------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)
mysql> GRANT USAGE ON *.* TO ‘user2‘@‘192.168.133.2‘ IDENTIFIED BY PASSWORD ‘*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0‘;
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT SELECT, INSERT, UPDATE ON `db1`.* TO ‘user2‘@‘192.168.133.2‘;
Query OK, 0 rows affected (0.00 sec)

技術分享圖片

mysql> show grants for user2@‘192.168.133.2‘;
+------------------------------------------------------------------------------------------------------------------+
| Grants for [email protected]                                                                                   |
+------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO ‘user2‘@‘192.168.133.2‘ IDENTIFIED BY PASSWORD ‘*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0‘ |
| GRANT SELECT, INSERT, UPDATE ON `db1`.* TO ‘user2‘@‘192.168.133.2‘                                               |
+------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

二、常用SQL語句

2.1 查詢語句的兩種形式

select count(*) from mysql.user; //查詢mysql庫中user表的行數

mysql> select count(*) from mysql.user;
+----------+
| count(*) |
+----------+
|       10 |
+----------+
1 row in set (0.00 sec)

select * from mysql.db\G;//查詢mysql庫中db表的所有內容

mysql> select * from mysql.db\G;
*************************** 1. row ***************************
                 Host: %
                   Db: test
                 User: 
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: Y
          Create_priv: Y
            Drop_priv: Y
           Grant_priv: N
      References_priv: Y
           Index_priv: Y

2.2 select語句在數據庫和表中對應的引擎不一樣,其計算統計時間也不同,不建議多使用

例如mysql下的user的表,用的是MYISAM引擎,會自動統計行數,運行效率快

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 create table user\G;
*************************** 1. row ***************************
       Table: user
Create Table: CREATE TABLE `user` (
  `Host` char(60) COLLATE utf8_bin NOT NULL DEFAULT ‘‘,
  `User` char(16) COLLATE utf8_bin NOT NULL DEFAULT ‘‘,
  `Password` char(41) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL DEFAULT ‘‘,
  `Select_priv` enum(‘N‘,‘Y‘) CHARACTER SET utf8 NOT NULL DEFAULT ‘N‘,
  `Insert_priv` enum(‘N‘,‘Y‘) CHARACTER SET utf8 NOT NULL DEFAULT ‘N‘,
  `Update_priv` enum(‘N‘,‘Y‘) CHARACTER SET utf8 NOT NULL DEFAULT ‘N‘,
  `Delete_priv` enum(‘N‘,‘Y‘) CHARACTER SET utf8 NOT NULL DEFAULT ‘N‘,
  .
  .
  .
   PRIMARY KEY (`Host`,`User`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT=‘Users and global privileges‘
1 row in set (0.01 sec)

對於db1下的t1表,其引擎是InnoDB,每次select時才開始統計行,運行效率低。(示例中的表格並未有數據,不能作為參考)

mysql> use db1;
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 create table t1;
+-------+---------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                        |
+-------+---------------------------------------------------------------------------------------------------------------------+
| t1    | CREATE TABLE `t1` (
  `id` int(4) DEFAULT NULL,
  `name` char(40) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+-------+---------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

2.3 查詢單個字段或者多個字段

mysql> select db from mysql.db;
+---------+
| db      |
+---------+
| test    |
| test\_% |
| db1     |
| db1     |
+---------+
4 rows in set (0.01 sec)

mysql> select db,user from mysql.db;
+---------+-------+
| db      | user  |
+---------+-------+
| test    |       |
| test\_% |       |
| db1     | user2 |
| db1     | user2 |
+---------+-------+
4 rows in set (0.00 sec)

2.4 使用萬能匹配符%,和like進行模糊匹配查詢

mysql> select * from mysql.db where host like ‘192.168.%‘;

技術分享圖片

mysql> mysql> select * from mysql.db where host like ‘192.168.%‘\G;
*************************** 1. row ***************************
                 Host: 192.168.133.1
                   Db: db1
                 User: user2
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          Delete_priv: N
          Create_priv: N
            Drop_priv: N
           Grant_priv: N
      References_priv: N
           Index_priv: N
           Alter_priv: N
Create_tmp_table_priv: N
     Lock_tables_priv: N
     Create_view_priv: N
       Show_view_priv: N
  Create_routine_priv: N
   Alter_routine_priv: N
         Execute_priv: N
           Event_priv: N
         Trigger_priv: N
*************************** 2. row ***************************
                 Host: 192.168.133.2
                   Db: db1
                 User: user2

2.5 MySQL中插入行

mysql> desc db1.t1;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(4)   | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> select * from db1.t1;
Empty set (0.01 sec)

mysql> insert into db1.t1 values (1, ‘abc‘);
Query OK, 1 row affected (0.02 sec)

mysql> select * from db1.t1;
+------+------+
| id   | name |
+------+------+
|    1 | abc  |
+------+------+
1 row in set (0.00 sec)

2.6 更改表的某一行

mysql> update db1.t1 set name=‘aaa‘ where id=1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from db1.t1;
+------+------+
| id   | name |
+------+------+
|    1 | aaa  |
+------+------+
1 row in set (0.00 sec)

2.7 清空某個表的數據,不刪除表只清空表的數據

mysql>  truncate table db1.t1;
Query OK, 0 rows affected (0.04 sec)

mysql> select * from db1.t1;
Empty set (0.00 sec)

2.8 刪除表drop

mysql> drop table db1.t1;
Query OK, 0 rows affected (0.03 sec)

mysql> select * from db1.t1;
ERROR 1146 (42S02): Table ‘db1.t1‘ doesn‘t exist

2.9 刪除數據庫

mysql> drop database db1;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from db1;
ERROR 1046 (3D000): No database selected

三、MySQL數據庫備份恢復

備份和恢復MySQL數據庫是非常重要的,要牢固掌握

3.1 用mysqldump命令備份,重定向到一個文本文檔中.

mysql> quit
Bye
[root@xavi ~]# mysqldump -uroot -pxavilinux mysql > /tmp/mysqlbak.sql;
Warning: Using a password on the command line interface can be insecure.

3.2 mysql數據恢復,反向重定向

[root@xavi ~]# mysql -uroot -pxavilinux -e "create database mysql2"
Warning: Using a password on the command line interface can be insecure.
[root@xavi ~]# mysql -uroot -pxavilinux mysql2 < /tmp/mysqlbak.sql
Warning: Using a password on the command line interface can be insecure.

3.3 進入該數據庫,檢查

[root@xavi ~]# mysql -uroot -pxavilinux mysql2
Warning: Using a password on the command line interface can be insecure.
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.6.35 MySQL Community Server (GPL)
mysql> select database();
+------------+
| database() |
+------------+
| mysql2     |
+------------+
1 row in set (0.00 sec)

備份數據庫下的表

mysql> quit
Bye
[root@xavi ~]# mysqldump -uroot -pxavilinux mysql user > /tmp/user.sql
Warning: Using a password on the command line interface can be insecure.

[root@xavi ~]# less /tmp/user.sql
  • less查看
[root@xavi ~]# less /tmp/user.sql
mysql  Ver 14.14 Distrib 5.6.35, for linux-glibc2.5 (x86_64) using  EditLine wrapper
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.

Usage: mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn‘t need to use
                      ‘rehash‘ to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
                      (Defaults to on; use --skip-auto-rehash to disable.)
  -A, --no-auto-rehash 
                      No automatic rehashing. One has to use ‘rehash‘ to get
                      table and field completion. This gives a quicker start of
                      mysql and disables rehashing on reconnect.

3.4 恢復某個數據表

[root@xavi ~]# mysql -uroot -pxavilinux mysql2 < /tmp/user.sql
Warning: Using a password on the command line interface can be insecure.

3.5 備份所有的庫

[root@xavi ~]# mysqldump -uroot -pxavilinux mysql2 >/tmp/user.sql
Warning: Using a password on the command line interface can be insecure.
[root@xavi ~]# less /tmp/mysql_all.sql

3.6 只備份表結構

[root@xavi ~]# mysqldump -uroot -pxavilinux -d mysql2 > /tmp/mysql2.sql
Warning: Using a password on the command line interface can be insecure.
[root@xavi ~]# less /tmp/mysql2.sql
[root@xavi ~]# less /tmp/mysql2.sql

-- MySQL dump 10.13  Distrib 5.6.35, for linux-glibc2.5 (x86_64)
--
-- Host: localhost    Database: mysql2
-- ------------------------------------------------------
-- Server version       5.6.35

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE=‘+00:00‘ */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `columns_priv`
--

DROP TABLE IF EXISTS `columns_priv`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `columns_priv` (
  `Host` char(60) COLLATE utf8_bin NOT NULL DEFAULT ‘‘,
  `Db` char(64) COLLATE utf8_bin NOT NULL DEFAULT ‘‘,
  `User` char(16) COLLATE utf8_bin NOT NULL DEFAULT ‘‘,
  `Table_name` char(64) COLLATE utf8_bin NOT NULL DEFAULT ‘‘,
  `Column_name` char(64) COLLATE utf8_bin NOT NULL DEFAULT ‘‘,
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `Column_priv` set(‘Select‘,‘Insert‘,‘Update‘,‘References‘) CHARACTER SET utf8 NOT NULL DEFAULT ‘‘,
  PRIMARY KEY (`Host`,`Db`,`User`,`Table_name`,`Column_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT=‘Column privileges‘;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `db`
--

DROP TABLE IF EXISTS `db`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `db` (

2.MySQL用戶管理,常用SQL語句,MySQL數據庫備份與恢復