2018-07-11(mysql常用操作)

13.1 設置更改root密碼

設置更改root密碼目錄概要

/usr/local/mysql/bin/mysql -uroot
更改環境變量PATH,增加mysql絕對路徑
mysqladmin -uroot password '123456'
mysql -uroot -p123456
密碼重置
vi /etc/my.cnf//增加skip-grant
重啓mysql服務 /etc/init.d/mysqld restart
mysql -uroot
use mysql;
update user set password=password('aminglinux') where user='root';

設置更改root密碼

root用戶是mysql的超級管理員用戶,和linux系統的root用戶類似,不過和Linux的不一樣
默認mysql的 root 用戶密碼是空的,直接使用mysql -uroot就可以連接上去,不需要輸入密碼,但是不安全,所以就需要設置一個密碼
爲了方便使用mysql服務,將mysql目錄加入到環境變量裏"export PATH=/usr/local/mysql/bin:$PATH" 永久生效加入到"/etc/profile"裏面,執行source /etc/profile 命令

1、查看mysql是否啓動 ps aux|grep mysql,如果沒有啓動,執行"/etc/init.d/mysqld start"

[root@lnmp-server ~]# ps aux |grep mysql
root        841  0.0  0.1 115432  1728 ?        S    10:33   0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/data/mysql/ --pid-file=/data/mysql//lnmp-server.pid
mysql      1057  6.4 45.1 1296356 451644 ?      Sl   10:33   0:04 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/data/mysql --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/var/log/mysqld.log --pid-file=/data/mysql//lnmp-server.pid --socket=/tmp/mysql.sock --port=3306
root       1231  0.0  0.0 112720   972 pts/0    R+   10:34   0:00 grep --color=auto mysql

2、設置mysql的root密碼
安裝完mysql後,默認root用戶是沒有密碼的,我們可以通過mysql自帶的命令mysqladmin給root設置一個密碼
格式:mysqladmin -uroot passwd '123456'

[root@lnmp-server ~]# mysqladmin -uroot password '123456'
Warning: Using a password on the command line interface can be insecure.

在設置密碼的時候,會看到有輸出信息,但這不是報錯信息,這是告訴你 你現在密碼在當前命令行顯示出來了,這樣不×××全
3、知道密碼的情況下更改密碼
格式:mysqladmin -uroot -p'123456' password '654321'

[root@lnmp-server ~]# mysqladmin -uroot -p'123456' password '654321'
Warning: Using a password on the command line interface can be insecure.

4、忘記密碼的情況修改
第一步:修改mysql的配置文件 /etc/my.cnf 在mysqld模塊下加入一行skip-grant,表示忽略授權

vi /etc/my.cnf   #在mysqld模塊下新增一行
skip-gant
[root@lnmp-server ~]# cat /etc/my.cnf
[mysqld]
port = 3306
basedir=/usr/local/mysql
datadir=/data/mysql/
socket=/tmp/mysql.sock
user=mysql
default-time-zone=system
default-storage-engine=InnoDB
log-error=/var/log/mysqld.log
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
skip-grant                          #增加這一行

第二步:在更改配置文件後,重啓mysql服務 /etc/init.d/mysqld restart

[root@lnmp-server ~]# /etc/init.d/mysqld restart
Shutting down MySQL. SUCCESS! 
Starting MySQL. SUCCESS!

第三步:連接mysql,這時候在輸入mysql -uroot ,會發現直接進入mysql,而不需要密碼了

[root@lnmp-server ~]# mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.36 Source distribution

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後,輸入:update mysql.user set password=password('123456') where user='root';

mysql> update mysql.user set password=password('123456') where user='root';
Query OK, 0 rows affected (0.06 sec)
Rows matched: 4  Changed: 4  Warnings: 0
mysql> flush privileges;                                  #刷新權限,讓它生效
Query OK, 0 rows affected (0.00 sec)
mysql> quit                                                    #輸入quit,退出mysql
Bye

注:提示說4行修改完畢,即使有些行是空的
第五步:更新完後修改mysql的配置文件 /etc/my.cnf 刪除增加的那一行skip-grant,去掉忽略授權,並重啓mysql服務 /etc/init.d/mysqld restart

[root@lnmp-server ~]# cat /etc/my.cnf
[mysqld]
port = 3306
basedir=/usr/local/mysql
datadir=/data/mysql/
socket=/tmp/mysql.sock
user=mysql
default-time-zone=system
default-storage-engine=InnoDB
log-error=/var/log/mysqld.log
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
#skip-grant                                           #這一行刪掉或者註釋掉

第六步:用更新完後密碼登陸mysql -uroot -p'123456'

[root@lnmp-server ~]# mysql -uroot -p'123456'
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 Source distribution

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> 

13.2 連接mysql

1、本地連接,默認使用sock連接
格式:mysql -uroot -p‘123456’

[root@lnmp-server ~]# mysql -uroot -p'123456'
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 Source distribution

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> 

2、使用ip端口連接遠程機器
格式:mysql -uroot -p'111111' -h[遠程mysql主機IP] -P[端口],mysql默認端口3306

[root@lnmp-server ~]# mysql -uroot -p'123456' -h127.0.0.1 -P3306
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 Source distribution

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> 

3、指定sock文件(只適合本機登陸)
格式:mysql -uroot -p'123456' -S/tmp/mysql.sock

[root@lnmp-server ~]# mysql -uroot -p'123456' -S/tmp/mysql.sock
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 Source distribution

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> 

4、不登陸mysql執行sql語句(常用於shell腳本)
格式:mysql -uroot -p123456 -e 'show databases;'

[root@lnmp-server ~]# mysql -uroot -p'123456' -e 'show databases;'
Warning: Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+

13.3 mysql常用命令

查詢庫 show databases;
切換庫 use mysql;
查看庫裏的表 show tables;
查看錶裏的字段 desc tb_name;
查看建表語句 show create table tb_name\G;
查看當前用戶 select user();
查看當前使用的數據庫 select database();
創建庫 create database db1;
創建表 use db1; create table t1(id int(4), name char(40));
查看當前數據庫版本 select version();
查看數據庫狀態 show status;
查看各參數 show variables; show variables like 'max_connect%';
修改參數 set global max_connect_errors=1000;
查看隊列 show processlist; show full processlist;

1、創建庫db1,並查看庫

mysql> create database db1;
Query OK, 1 row affected (0.00 sec)
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| db1                |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.00 sec)

2、使用db1庫,創建表tb1(新建字段id 整數型長度爲4 ,字段name 字符型長度爲40),並查看錶

mysql> use db1;
Database changed
mysql> create table tb1 (id int(4),name char(40));
Query OK, 0 rows affected (0.13 sec)
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| tb1           |
+---------------+
1 row in set (0.00 sec)

3、查看錶的字段

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

4、查看建表語句

mysql> show create table tb1\G;
*************************** 1. row ***************************
       Table: tb1
Create Table: CREATE TABLE `tb1` (
  `id` int(4) DEFAULT NULL,
  `name` char(40) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
ERROR: 
No query specified

注:\G是爲了豎型顯示,更清晰
5、查看當前用戶和庫

mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

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

6、查詢數據庫版本

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.6.36    |
+-----------+
1 row in set (0.00 sec)

7、查看各參數 show variables; show variables like 'max_connect%'; // mysql下 % 爲通配符

mysql> show variables like 'max_connect%';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| max_connect_errors | 100   |
| max_connections    | 151   |
+--------------------+-------+
2 rows in set (0.00 sec)

8、修改參數 set global max_connect_errors=1000; ——>僅在內存中生效,若想重啓生效修改/etc/my.cnf

mysql> set global max_connect_errors=1000;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'max_connect%';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| max_connect_errors | 1000  |
| max_connections    | 151   |
+--------------------+-------+
2 rows in set (0.00 sec)

9、查看隊列
show processlist; //查看庫的狀況,比如,那些用戶在連,做了些什麼操作,是否鎖表
show full processlist; //查看到的對列,最後一個會非常完成的顯示出來

mysql> show processlist;
+----+------+-----------+------+---------+------+-------+------------------+
| Id | User | Host      | db   | Command | Time | State | Info             |
+----+------+-----------+------+---------+------+-------+------------------+
| 14 | root | localhost | db1  | Query   |    0 | init  | show processlist |
+----+------+-----------+------+---------+------+-------+------------------+
1 row in set (0.00 sec)

mysql> show full  processlist;
+----+------+-----------+------+---------+------+-------+------------------------+
| Id | User | Host      | db   | Command | Time | State | Info                   |
+----+------+-----------+------+---------+------+-------+------------------------+
| 14 | root | localhost | db1  | Query   |    0 | init  | show full  processlist |
+----+------+-----------+------+---------+------+-------+------------------------+
1 row in set (0.00 sec)

說明:在mysql中也支持上下方向鍵查看執行過的命令,命令歷史保存在用戶家目錄下.mysql_history文件中

13.4 mysql用戶管理

1、創建一個用戶並授權所有庫和表的所有權限
格式:grant all on . to 'user1' identified by 'passwd';

mysql> grant all on *.* to 'luo' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
mysql> select user from mysql.user;
+------+
| user |
+------+
| luo  |
| root |
| root |
|      |
| root |
|      |
| root |
+------+
7 rows in set (0.00 sec)

2、針對指定的條件授權
格式:grant SELECT,UPDATE,INSERT on db1.* to 'user2'@'192.168.180.1' identified by 'passwd';
語句說明:授權查詢 更新 插入 在數據庫 db1所有表上 給來源ip爲192.168.180.1的用戶user2,並設定密碼

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

3、針對指定的條件授權
格式:grant all on db1.* to 'user3'@'%' identified by 'passwd';
語句說明:授權所有權限在數據庫 db1所有表上 給來源ip爲所有的用戶user2,並設定密碼 ,%表示通配,即所有的

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

4、show grants;
show grants;看的是root

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

5、查看剛纔授權的用戶user2@'192.168.133.132'

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

13.5 常用sql語句

增刪改查,就是mysql和其他關係型數據庫常用的select語句操作命令
查詢語句

首先登錄root下的mysql mysql -uroot -p111111
使用db1庫 use db1;
查看當前庫的所有表show tables;
查看錶的行數 select count(*) from mysql.user;
庫和表中間有個分割符,就是用點 . 分割

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

就是說user表有10行內容
查看所有的內容 select from mysql.db;(這樣看起來會很亂) ——>可以在後面加上\G,如select from mysql.db\G;
這裏的 * 表示查看所有內容
查看db庫的所有內容 select db from mysql.db; 第一個db是字段

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

查db字段和user字段 select db,user from mysql.db;

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

模糊查詢 select * from mysql.db where host like '192.168.%'; like 就是模糊匹配
插入語句

查看創建的表

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

查看db1.tb1表的內容,會發現爲空 select * from db1.tb1;
插入數據到

insert into db1.tb1 values (1, 'abc');`

插入1, 'abc'到db1.tb1表
再來查詢db1.tb1

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

這樣就成功了插入了一條數據,在插入的時候 name 這個字段應該是是一個字符串,字符串需要加上一個單引號 ' ' ,數字可以不加單引號

mysql> insert into db1.tb1 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)

這裏沒有做限制,這裏id和name都可以是相同的,同一個字段裏有相同的數字,相同的值 ,也可以做一些限制,在插入相同的id的時候,就會衝突
update操作

更改db1.t1表 的字符串爲name 的數據 和 字符串爲id 的數據
update db1.tb1 set name='aaa' where id=1;

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

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

delete操作

刪除db1.tb1表 的數據 和 字符串爲id 的數據

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

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

truncate清空一個表

清空表數據 truncate table db1.tb1;
即使表的數據清空了,但表的字段依舊存在的

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

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

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

truncate 只是清空的內容,而drop 會清空表的數據並清除表的框架
drop 會把表的框架也丟掉 drop table db1.tb1;

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

mysql> select * from db1.tb1;    //因爲表的架構已經不存在了
ERROR 1146 (42S02): Table 'db1.t1' doesn't exist
mysql> 

刪除庫

drop database db1;

總結

在使用mysql的時候,少用 這樣的操作,因爲若是一個表裏面的內容很多,select count()這樣操作就會很耗時,浪費資源
數據庫中常用引擎是myisam和innodb,默認mysql庫裏面都是使用的myisam引擎
特點:myisam引擎,能自動去統計有多少行
在select count()查看錶的時候會很快
use mysql;
show create table user\G;
特點:innodb引擎,不會自動統計行數,每次去查詢,每次去統計行數,就會很耗時
use db1
show create table t1;
所以select count(
)這種操作儘量減少,會耗費太多資源

13.6 mysql數據庫備份恢復

備份庫
備份mysql庫 mysqlbak.sql文件就是mysql的備份庫文件

[root@lnmp-server ~]# mysqldump -uroot -p123456 mysql>/tmp/mysqlbak.sql
Warning: Using a password on the command line interface can be insecure.
[root@lnmp-server ~]# ll /tmp/mysqlbak.sql 
-rw-r--r-- 1 root root 657033 7月  12 13:14 /tmp/mysqlbak.sql

我們可以通過mysqlbak.sql來恢復數據庫,還可以恢復到另外一個數據庫裏面去
恢復庫
這裏把數據恢復到新的庫裏,創建一個新的庫mysql2

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

進入到數據庫裏面,在後面加一個mysql2 就會進入到mysql2數據庫裏面

[root@lnmp-server ~]# mysql -uroot -p123456 mysql2
Warning: Using a password on the command line interface can be insecure.

查看數據庫

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

備份表
針對庫裏面的某一個表去做備份,只需要在 庫後面 加上 表名字 即可備份,先庫 在表,中間是空格
備份表格式:mysqldump -uroot -p123456 databasename tablename > /tmp/user.sql

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

恢復表
恢復表的時候,只需要寫庫的名字,不需要去寫表的名字
恢復表格式:mysql -uroot -p123456 mysql < /tmp/user.sql

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

恢復表到mysql2庫

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

備份所有的庫
格式:mysqldump -uroot -p123456 -A >/tmp/mysql_all.sql
-A 表示all所有的意思

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

只備份表結構
格式:mysqldump -uroot -p123456 -d mysql > /tmp/mysql.sql
不需要表的數據,只需要表的結構
備份mysql2的表結構

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

兩個機器的庫備份,一個庫備份到另一臺機器上
解決:
首先兩臺機器能夠通信
然後mysqldump -h 遠程mysql-ip -uuser-ppassword dbname > /本地backup.sql
這樣即可備份

擴展:
使用xtrabackup備份innodb引擎的數據庫 innobackupex 備份 Xtrabackup 增量備份 http://zhangguangzhi.top/2017/08/23/innobackex%E5%B7%A5%E5%85%B7%E5%A4%87%E4%BB%BDmysql%E6%95%B0%E6%8D%AE/#%E4%B8%89%E3%80%81%E5%BC%80%E5%A7%8B%E6%81%A2%E5%A4%8Dmysql
mysql5.7 root密碼更改 http://www.apelearn.com/bbs/thread-7289-1-1.html
myisam 和innodb引擎對比 http://www.pureweber.com/article/myisam-vs-innodb/
mysql 配置詳解: http://blog.linuxeye.com/379.html
mysql調優: http://www.aminglinux.com/bbs/thread-5758-1-1.html
同學分享的親身mysql調優經歷: http://www.apelearn.com/bbs/thread-11281-1-1.html
SQL語句教程 http://www.runoob.com/sql/sql-tutorial.html
什麼是事務?事務的特性有哪些? http://blog.csdn.net/yenange/article/details/7556094

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