十三週二次課(6月20日)

13.4 MySQL用戶管理

場景,爲了安全,新建的站點,創建新的用戶,或者給予使用已有賬戶,給予權限
MySQL創建用戶以及授權

mysql> grant all on *.* to 'aiker'@'127.0.0.1' identified by '12345678';
Query OK, 0 rows affected (0.01 sec)

mysql> 

 grant all on *.* to ‘aiker’ identified by ‘passwd’;
 grant all on *.* to ‘aiker’@’127.0.0.1’ identified by ‘passwd’;

grant 授權
all (查看,創建,刪除等等)
aiker’@’127.0.0.1’ 指定用戶@指定來源IP (指定用戶可以寫%,表示所有的IP)如果指定了來源IP,那麼只能通過來源IP登錄
. 所有庫,所有表
命令輸錯,直接輸入“ ; ”分號退出

使用用戶aiker 登錄mysql 看下

[root@localhost ~]# mysql -uaiker -p12345678
Warning: Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'aiker'@'localhost' (using password: YES)
[root@localhost ~]# 

不能登錄,爲什麼不行呢,因爲默認用的是socket
授權一個ip

[root@localhost ~]# mysql -uaiker -p12345678 -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.36 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> quit
Bye
[root@localhost ~]# 

用socket去連
先登錄root,再定義localhost

[root@localhost ~]# mysql -uroot -paiker12345678
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 4
Server version: 5.6.36 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> grant all on *.* to 'aiker'@'localhost' identified by '12345678';
Query OK, 0 rows affected (0.00 sec)

mysql> 

退出來,打錯了用 分號 ; 退出來,除了用 quit 之外還可以用exit ctrl d

mysql> uit
    -> quit
    -> ;
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 'uit
quit' at line 1
mysql> quit
Bye
[root@localhost ~]# 

再來試下aiker 登錄,就可以了

[root@localhost ~]# mysql -uaiker -p12345678
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.36 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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
Bye
[root@localhost ~]# 

用來查看指定用戶的授權是什麼,show grants; (指定root)
show grants for [email protected];(指定172.16.20.222)

[root@localhost ~]# mysql -uroot -paiker12345678
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 6
Server version: 5.6.36 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> show grants;
+----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                                              |
+----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*1836D7557E753782F1509748BD403456701A0D2F' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION                                                                           |
+----------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> 

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

mysql> 

再來把gavin 做一個授權, 再show grants;
show grants;看的是root

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

mysql> 

mysql> show grants;
+----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                                              |
+----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*1836D7557E753782F1509748BD403456701A0D2F' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION                                                                           |
+----------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> 

展示gavin的 授權

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

mysql> 

mysql> GRANT USAGE ON *.* TO 'gavin'@'172.16.20.220' IDENTIFIED BY PASSWORD '*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0'
    -> ;
Query OK, 0 rows affected (0.00 sec)

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

mysql> 

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

mysql> 

13.5 常用sql語句

先到mysql下

[root@localhost ~]# mysql -uroot -paiker12345678
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 8
Server version: 5.6.36 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> 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> 

查看錶的行數 select count(*) from mysql.user;

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

mysql> 

查看所有的內容

mysql> select * from mysql.db;
+---------------+---------+-------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-----------------------+------------------+------------------+----------------+---------------------+--------------------+--------------+------------+--------------+
| Host          | Db      | User  | Select_priv | Insert_priv | Update_priv | Delete_priv | Create_priv | Drop_priv | Grant_priv | References_priv | Index_priv | Alter_priv | Create_tmp_table_priv | Lock_tables_priv | Create_view_priv | Show_view_priv | Create_routine_priv | Alter_routine_priv | Execute_priv | Event_priv | Trigger_priv |
+---------------+---------+-------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-----------------------+------------------+------------------+----------------+---------------------+--------------------+--------------+------------+--------------+
| %             | test    |       | Y           | Y           | Y           | Y           | Y           | Y         | N          | Y               | Y          | Y          | Y                     | Y                | Y                | Y              | Y                   | N                  | N            | Y          | Y            |
| %             | test\_% |       | Y           | Y           | Y           | Y           | Y           | Y         | N          | Y               | Y          | Y          | Y                     | Y                | Y                | Y              | Y                   | N                  | N            | Y          | Y            |
| 172.16.20.222 | db1     | gavin | Y           | Y           | Y           | N           | N           | N         | N          | N               | N          | N          | N                     | N                | N                | N              | N                   | N                  | N            | N          | N            |
| 172.16.20.220 | db1     | gavin | Y           | Y           | Y           | N           | N           | N         | N          | N               | N          | N          | N                     | N                | N                | N              | N                   | N                  | N            | N          | N            |
+---------------+---------+-------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-----------------------+------------------+------------------+----------------+---------------------+--------------------+--------------+------------+--------------+
4 rows in set (0.00 sec)

mysql> 

查看db庫的所有內容
查看錶,用戶

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

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

mysql> 

模糊查詢。like 模糊匹配

mysql> select * from mysql.db where host like '172.16.20.%';
+---------------+-----+-------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-----------------------+------------------+------------------+----------------+---------------------+--------------------+--------------+------------+--------------+
| Host          | Db  | User  | Select_priv | Insert_priv | Update_priv | Delete_priv | Create_priv | Drop_priv | Grant_priv | References_priv | Index_priv | Alter_priv | Create_tmp_table_priv | Lock_tables_priv | Create_view_priv | Show_view_priv | Create_routine_priv | Alter_routine_priv | Execute_priv | Event_priv | Trigger_priv |
+---------------+-----+-------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-----------------------+------------------+------------------+----------------+---------------------+--------------------+--------------+------------+--------------+
| 172.16.20.222 | db1 | gavin | Y           | Y           | Y           | N           | N           | N         | N          | N               | N          | N          | N                     | N                | N                | N              | N                   | N                  | N            | N          | N            |
| 172.16.20.220 | db1 | gavin | Y           | Y           | Y           | N           | N           | N         | N          | N               | N          | N          | N                     | N                | N                | N              | N                   | N                  | N            | N          | N            |
+---------------+-----+-------+-------------+-------------+-------------+-------------+-------------+-----------+------------+-----------------+------------+------------+-----------------------+------------------+------------------+----------------+---------------------+--------------------+--------------+------------+--------------+
2 rows in set (0.00 sec)

mysql> select * from mysql.db where host like '172.16.20.%'\G;   // \G是按照豎行排行
*************************** 1. row ***************************
                 Host: 172.16.20.222
                   Db: db1
                 User: gavin
          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: 172.16.20.220
                   Db: db1
                 User: gavin
          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 rows in set (0.00 sec)

ERROR: 
No query specified

mysql> 

插入1, ‘abc’到db1.t1表

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.09 sec)

mysql> 

mysql> select * from db1.ti;
ERROR 1146 (42S02): Table 'db1.ti' doesn't exist
mysql> select * from db1.t1;
Empty set (0.09 sec)

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

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

mysql> 

mysql> insert into db1.t1 values (1, '234');
Query OK, 1 row affected (0.01 sec)

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

mysql> 

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

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

mysql> 

更改db1.t1表 的字符串爲name 的數據 和 字符串爲id 的數據

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

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

mysql> 

mysql> update db1.t1 set id=2 where name='aaa';
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

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

mysql> 

刪除t1表

mysql> delete from db1.t1 where id=2;
Query OK, 3 rows affected (0.00 sec)

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

mysql> 

重新插入一個ti表

mysql> insert into db1.t1 values (1, '234');
Query OK, 1 row affected (0.00 sec)

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

mysql> 

truncate db1.t1; 僅僅是清除表裏的數據,清空數據

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

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

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.00 sec)

mysql> 

drop table t1; 連錶帶殼全部清除 丟掉表

mysql> drop table t1;
Query OK, 0 rows affected (0.01 sec)

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

drop database db1; 把數據庫給幹掉了

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

mysql> 

myisam引擎的庫的好處是,能自動去統計行數

儘量少用 * 這樣操作,如果是大表會很耗時

13.6 MySQL數據庫備份恢復

[root@localhost ~]# mysqldump -uroot -paiker12345678 mysql

  `query_time` time NOT NULL,
  `lock_time` time NOT NULL,
  `rows_sent` int(11) NOT NULL,
  `rows_examined` int(11) NOT NULL,
  `db` varchar(512) NOT NULL,
  `last_insert_id` int(11) NOT NULL,
  `insert_id` int(11) NOT NULL,
  `server_id` int(10) unsigned NOT NULL,
  `sql_text` mediumtext NOT NULL,
  `thread_id` bigint(21) unsigned NOT NULL
) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='Slow log';
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

 Dump completed on 2018-01-30 23:00:48
[root@localhost ~]# 

這些都是就是這個mysql庫裏的東西,備份就是把這些東西 重定向到指定的文件中去

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

mysqlbak.sql就是我們備份的 msyql庫文件
創建一個新的mysql2庫

[root@localhost ~]# mysql -uroot -paiker12345678 -e "create database mysql2"
Warning: Using a password on the command line interface can be insecure.
[root@localhost ~]# 

要給它恢復回去就用這個命令

[root@localhost ~]# mysql -uroot -paiker12345678 mysql2 < /tmp/mysqlbak.sql
Warning: Using a password on the command line interface can be insecure.
[root@localhost ~]# mysql -uroot -paiker12345678 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 13
Server version: 5.6.36 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, 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> 

這個mysql2 和mysql一樣

mysql> select database();
+------------+
| database() |
+------------+
| mysql2     |
+------------+
1 row in set (0.00 sec)

mysql> show tables;
+---------------------------+
| Tables_in_mysql2          |
+---------------------------+
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| 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                      |
+---------------------------+
28 rows in set (0.00 sec)

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                        |
| event                     |
| func                      |
| general_log               |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| 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                      |
+---------------------------+
28 rows in set (0.01 sec)

mysql> 
mysql> quit
Bye

備份 表user

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

[root@localhost ~]# less /tmp/user.sql

 Table structure for table `user`

DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
  `Host` char(60) COLLATE utf8_bin NOT NULL DEFAULT '',
/tmp/user.sql

恢復 一個表,恢復mysql2 裏面的user表

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

備份所有庫

[root@localhost ~]# mysqldump -uroot -paiker12345678 -A > /tmp/mysql_all.sql
Warning: Using a password on the command line interface can be insecure.
[root@localhost ~]# 

只備份表結構,不備份數據 mysqldump -uroot -paiker12345678 -d mysql2 > /tmp/mysql2.sql

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

總結

備份庫

mysqldump -uroot -p123456 mysql > /tmp/mysql.sql

恢復庫 //恢復是,必須保證目錄一致

mysql -uroot -p123456 mysql < /tmp/mysql.sql

備份表

mysqldump -uroot -p123456 mysql user > /tmp/user.sql

恢復表

mysql -uroot -p123456 mysql < /tmp/user.sql

備份所有庫

mysqldump -uroot -p -A >/tmp/123.sql

只備份表結構

mysqldump -uroot -p123456 -d mysql > /tmp/mysql.sql

在mysql下進行導入數據

進入到mysql ,切換至需要導入的數據庫,執行source 文件所在路徑;例如:

sql>source /root/testbak.sql

擴展

SQL語句教程

http://www.runoob.com/sql/sql-tutorial.html

什麼是事務?事務的特性有哪些?

概念
事務(Transaction)是訪問並可能更新數據庫中各種數據項的一個程序執行單元(unit)。事務通常由高級數據庫操縱語言或編程語言(如SQL,C++或Java)書寫的用戶程序的執行所引起,並用形如begin transaction和end transaction語句(或函數調用)來界定。事務由事務開始(begin transaction)和事務結束(end transaction)之間執行的全體操作組成。

例如:在關係數據庫中,一個事務可以是一條SQL語句,一組SQL語句或整個程序。

特性

  事務是恢復和併發控制的基本單位。

  事務應該具有4個屬性:原子性、一致性、隔離性、持續性。這四個屬性通常稱爲ACID特性。

  原子性(atomicity)。一個事務是一個不可分割的工作單位,事務中包括的操作要麼都做,要麼都不做。

  一致性(consistency)。事務必須是使數據庫從一個一致性狀態變到另一個一致性狀態。一致性與原子性是密切相關的。

  隔離性(isolation)。一個事務的執行不能被其他事務干擾。即一個事務內部的操作及使用的數據對併發的其他事務是隔離的,併發執行的各個事務之間不能互相干擾。

  持久性(durability)。持續性也稱永久性(permanence),指一個事務一旦提交,它對數據庫中數據的改變就應該是永久性的。接下來的其他操作或故障不應該對其有任何影響。

根據binlog恢復指定時間段的數據

如果不小心對數據庫進行誤操作,而又沒有及時備份怎麼辦?這恐怕是廣大的coder經常遇到的一類問題。
我今天就因爲不小心刪除了某個數據庫,但最後的備份是1個禮拜前的,唯一能解決的辦法就是通過mysqlbinlog來恢復了。解決方案如下:

如果MySQL服務器啓用了二進制日誌,你可以使用mysqlbinlog工具來恢復從指定的時間點開始(例如,從你最後一次備份)直到現在或另一個指定的時間點的數據。
關於啓用二進制日誌的信息,參見5.11.3節,“二進制日誌”。對於mysqlbinlog的詳細信息,參見mysql手冊8.6節,“mysqlbinlog:用於處理二進制日誌文件的實用工具”。
要想從二進制日誌恢復數據,你需要知道當前二進制日誌文件的路徑和文件名。
一般可以從配置文件(一般情況,Linux下爲my.cnf ,windows系統下爲my.ini,取決於你的系統)中找到路徑。如果未包含在選項文件中,當服務器啓動時,可以在命令行中以選項的形式給出。
啓用二進制日誌的選項爲–log-bin。
要想確定當前的二進制日誌文件的文件名,輸入下面的MySQL語句:

SHOW BINLOG EVENTS \G;

或者還可以從命令行輸入下面的內容:

mysql –user=root -pmypasswd -e ‘SHOW BINLOG EVENTS \G’ 將密碼mypasswd替換爲你的MySQL服務器的root密碼。

比如得到的日誌文件名爲:
mysql-bin.000001 1. 指定恢復時間 對於MySQL5.1.54,可以在mysqlbinlog語句中通過–start-date和–stop-date選項指定DATETIME格式的起止時間。

舉例說明,比如在今天下午14:02(今天是2012年3月15日),不小心執行SQL語句刪除了一個數據表,但發現沒有最新的備份(當然,這只是開發環境,並不是正式的生產環境,正式環境還得定時做數據備份)。要想恢復表和數據,可以通過mysqlbinlog恢復指定時間的備份,輸入:

mysqlbinlog –stop-date=”2012-03-15 14:02:00″ /data1/log/mysql/mysql-bin.000001  | mysql -u root -pmypasswd

該命令將恢復截止到在–stop-date選項中以DATETIME格式給出的日期和時間的所有數據。

#備註,可以使用mysqlbinlog 先查看binlog日誌文件的所有操作確定時間點

如果你沒有檢測到輸入的錯誤的SQL語句,可能你想要恢復後面發生的數據庫活動。
根據這些,你可以用起使日期和時間再次運行mysqlbinlog:

mysqlbinlog –start-date=”2012-03-15 00:01:00″ /data1/log/mysql/mysql-bin.000001  | mysql -u root -pmypasswd

在該行中,從今天凌晨0:01登錄的SQL語句將運行,組合執行前夜的轉儲文件和mysqlbinlog的兩行可以將所有數據恢復到今天凌晨0:01前一秒鐘。
你應檢查日誌以確保時間確切。下一節介紹如何實現。

  1. 指定時間段恢復 通過mysqlbinlog –start-date 和–stop-date恢復指定時間段的數據庫活動記錄,如下:
    mysqlbinlog –start-date=”2012-03-09 02:00:00″ –stop-date=”2012-03-15 14:00:00″ /data1/log/mysql/mysql-bin.000001 > /tmp/mysql_restore_030915.sql

    通過這種方式,就能獲取最後一個備份的文件時間2012-03-09 02:00:00到今天刪除數據庫之前2012-03-15 14:02這段時間的數據庫活動事務操作

mysql字符集調整

字符集是一套符號和編碼的規則,不論是在oracle數據庫還是在mysql數據庫,都存在字符集的選擇問題。對於數據庫來說,字符集又是比較重要的,因爲數據庫存儲的數據大部分都是各種文字,字符集對於數據庫的存儲、處理性能以及數據遷移都有重要的影響。

如果在數據庫創建階段沒有正確選擇字符集,那麼可能在後期需要更換字符集,而字符集的更換是代價比較高的操作,也存在一定的風險,所以我們建議在應用開始階段,就按照需求正確的選擇合適的字符集,儘量避免後期不必要的調整。

mysql編譯安裝時,指定字符集的方法:

./configure  --with-charset=utf8

mysql的字符集有4個級別的默認設置:服務器級、數據庫級、表級和字段級。分別在不同的地方設置,作用也不相同。
1、服務器字符集設定,在mysql服務啓動的時候確定。
可以在my.cnf中設置:

[mysql]

### 默認字符集爲utf8

default-character-set=utf8

[mysqld]
### 默認字符集爲utf8

default-character-set=utf8

### (設定連接mysql數據庫時使用utf8編碼,以讓mysql數據庫爲utf8運行)

init_connect='SET NAMES utf8'

或者在啓動選項中指定:
mysqld --default-character-set=utf8

如果沒有特別的指定服務器字符集,默認使用latin1(ISO-8859-1的別名)作爲服務器字符集。上面三種設置的方式都只指定了字符集,沒有去做校對,我們可以用show variables like 'char%';命令查詢當前服務器的字符
集和校對規則。

mysql>show variables like 'char%';

   +--------------------------+----------------------------+

  | 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/ |

  +--------------------------+----------------------------+

注:如果增加default-character-set=utf8後,MYSQL啓動報錯。可以用character_set_server=utf8來取代default-character-set=utf8,就能正常啓動了。這是因爲MYSQL不同版本識別的問題。

2、數據庫級

創建數據庫時指定字符集

mysql>CREATE DATABASE my_db default charset utf8 COLLATE utf8_general_ci;

#注意後面這句話 "COLLATE utf8_general_ci",大致意思是在排序時根據utf8編碼格式來排序

如果指定了數據庫編碼,那麼在這個數據庫下創建的所有數據表的默認字符集都會是utf8了

修改MYSQL數據庫編碼,如果是MYSQL數據庫編碼不正確,可以在MYSQL執行如下命令:

ALTER DATABASE my_db DEFAULT CHARACTER SET utf8;  

以上命令就是將MYSQL的my_db數據庫的編碼設爲utf8

3、 表級

創建表時指定字符集

mysql>create table my_table (name varchar(20) not null default '')type=myisam default charset utf8;

#這句話就是創建一個表,指定默認字符集爲utf8

修改MYSQL表的編碼:

ALTER TABLE my_table DEFAULT CHARACTER SET utf8;

以上命令就是將一個表my_table的編碼改爲utf8

4、 字段級

alter table test add column address varchar(110) after stu_id;

在stu_id後增加一個字段address

alter table test add id int unsigned not Null auto_increment primary key;

修改字段的編碼:

ALTER TABLE `test` CHANGE `name` `name` VARCHAR( 45 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL

以上命令就是將MYSQL數據庫test表中name的字段編碼改爲utf8

在命令行下插入漢字時如下代碼:

set names utf8;有時候這一句很關鍵!

insert into charset values('王達');

注意:alter修改的方法不能更新已有記錄的字符集,只是對新創建的表和記錄生效。對已有記錄字符集的調整,需要先將數據導出,經過適當調整後重新導入纔可以完全修改編碼。

導出導入的字符調整方法:

導出表結構

mysqldump -uroot -pmysql --default-character-set=latin1 -d  my_db> createtab.sql

手工修改createtab.sql表結構定義中的字符集爲新的字符集

1、導出所有記錄

mysqldump -uroot -pmysql --quick --no-create-info --extended-insert --default-character-set=latin1 --host=localhost  my_db> data.sql

2、打開data.sql,將set names latin1修改成set names utf8

:%s/latin1/utf8/g

全文替換

3、使用新的字符集創建新的數據庫

create database  mydata  default charset utf8;

4、創建表,執行createtab.sql

mysql -uroot -pmysql mydata<creattab.sql

5、導入數據

mysql -uroot -pmysql mydata<data.sql

注意一點就是目標字符集要大於等於源字符集,否則會丟失一部分不支持的漢字數據。

附:舊數據升級辦法

以原來的字符集爲latin1爲例,升級成爲utf8的字符集。原來的表: old_table (default charset=latin1),新表:new_table(default charset=utf8)。

第一步:導出舊數據

mysqldump --default-character-set=latin1 -hlocalhost -uroot -B my_db --tables old_table > old.sql

第二步:轉換編碼

iconv -t utf8  -f latin1 -c old.sql > new.sql

在這裏,假定原來的數據默認是latin1編碼。

第三步:導入

修改old.sql,增加一條sql語句: "SET NAMES utf8;",保存。

mysql -hlocalhost -uroot my_db < new.sql

大功告成!

Mysql collate規則:

*_bin: 表示的是binary case sensitive collation,也就是說是區分大小寫的
*_cs: case sensitive collation,區分大小寫
*_ci: case insensitive collation,不區分大小寫

使用xtrabackup備份innodb引擎的數據庫

innobackex工具備份mysql數據
xtrbackup只能用於備份innodb引擎的數據庫,而innobackex 既可以備份innodb引擎的數據庫,也可以備份myisam引擎的數據庫。備份時也可分爲全量備份和增量備份

一、安裝innobackex
使用官網的yum源,方便安裝

[root@axiang-02 ~]# rpm -ivh https://www.percona.com/redir/downloads/percona-release/redhat/percona-release-0.1-4.noarch.rpm
[root@axiang-02 ~]# yum install percona-xtrabackup

二、全量備份mysql
2.1、創建並授權備份用戶

我們可以直接授權all權限,但是不符合安全原則

mysql -uroot -paxianglinux
grant reload,lock tables,replication client on *.* to 'backupuser'@'localhost'  identified  by 'axianglinux';
flush  privileges;
權限爲reload,lock tables,replication client

2.2、全部備份

[root@axiang-02 ~]# mkdir /data/backup
[root@axiang-02 ~]# innobackupex --defaults-file=/etc/my.cnf --user=backupuser  --password='axianglinux' -S /tmp/mysql.sock /data/backup
defaults-file=/etc/my.cnf指定配置文件位置是爲了獲得datadir位置
備份完成後,會在指定的保存目錄中生成一個時間戳目錄

如圖,備份失敗也會出現

三、全量備份恢復
3.1、模擬誤刪除MySQL數據目錄故障

[root@axiang-02 ~]# /etc/init.d/mysqld  stop  
[root@axiang-02 ~]# mv /data/mysql /data/mysql.bak
[root@axiang-02 ~]# mkdir /data/mysql
[root@axiang-02 ~]# chown -R mysql:mysql /data/mysql
 如果權限沒給 -R 則恢復後無法開啓MySQL服務。如上圖

3.2、恢復

[root@axiang-02 ~]# ls /data/backup/
2017-08-28_20-47-25

[root@axiang-02 ~]# innobackupex  --use-memory=512M  --apply-log /data/backup/2017-08-28_20-47-25/
[root@axiang-02 ~]# innobackupex  --defaults-file=/etc/my.cnf  --copy-back /data/backup/2017-08-28_20-47-25/
[root@axiang-02 ~]# /etc/init.d/mysqld start
Starting MySQL. SUCCESS! 

四、增量備份
之前我們已經進行了全量備份,經過操作,一段時間後重新全量備份的話,需要耗費的資源較多,這時我們就可以使用增量備份了。

兩次增量備份

[root@axiang-02 ~]# rm -rf /data/backup/*
[root@axiang-02 ~]# innobackupex --defaults-file=/etc/my.cnf --user=backupuser  --password='axianglinux' -S /tmp/mysql.sock /data/backup
[root@axiang-02 ~]# mysql -uroot -paxianglinux -e 'drop database bbs;'
[root@axiang-02 ~]# innobackupex  --defaults-file=/etc/my.cnf  --user=backupuser  --password='axianglinux'  -S /tmp/mysql.sock  --incremental  /data/backup  --incremental-basedir=/data/backup/2017-08-28_23-18-20
[root@axiang-02 ~]# mysql -uroot -paxianglinux -e 'drop database blog;'
[root@axiang-02 ~]# innobackupex  --defaults-file=/etc/my.cnf  --user=backupuser  --password='axianglinux'  -S /tmp/mysql.sock  --incremental  /data/backup  --incremental-basedir=/data/backup/2017-08-28_23-24-32

在每個備份的時間戳目錄下面都有一個檢查點。可以確定恢復順序

五、順序恢復
模擬故障,移除原有數據

[root@axiang-02 ~]# /etc/init.d/mysqld stop
[root@axiang-02 ~]# mv /data/mysql /data/mysql.backup
[root@axiang-02 ~]# mkdir /data/mysql
[root@axiang-02 ~]# chown -R mysql:mysql /data/mysql

恢復

innobackupex --apply-log --redo-only /data/backup/2017-08-28_23-18-20
innobackupex --apply-log --redo-only /data/backup/2017-08-28_23-18-20 --incremental-dir=/data/backup/2017-08-28_23-24-32
innobackupex --apply-log /data/backup/2017-08-28_23-18-20 --incremental-dir=/data/backup/2017-08-28_23-27-39
innobackupex --copy-back /data/backup/2017-08-28_23-18-20/
chown -R mysql:mysql /data/mysql
/etc/init.d/mysqld start

相關視頻
鏈接:http://pan.baidu.com/s/1miFpS9M 密碼:86dx
鏈接:http://pan.baidu.com/s/1o7GXBBW 密碼:ue2f

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章