1. 设置更改root密码

MySQL的root和Linux的root是不一样的,默认是没有密码的,需要设置。

1.1 配置MySQL环境变量

首次直接使用mysql会提示‘未找到命令’,这是因为将该命令没有加入环境变量。如果要使用命令,需要使用它的绝对路径:/usr/local/mysql/bin/mysql。为了方便,建议将其加入系统的环境变量。

[root@host ~]# export PATH=$PATH:/usr/local/mysql/bin/
#这是将命令路径暂时加入环境变量,系但是统重启后该变量会失效,最好将其加入环境变量配置文件

[root@host ~]# vim /etc/profile
…… #添加
export PATH=$PATH:/usr/local/mysql/bin/

[root@host ~]# source /etc/profile   //刷新刚刚的配置文件,否则不生效

首次登陆mysql,root用户是没有密码的,可以直接登录

[root@host ~]# mysql -uroot  //指定用户名
Welcome to the MySQL monitor.  Commands end with ; or \g.
……
mysql> quit    //输入quit可以退出

1.2 设置密码

[root@host ~]# mysqladmin -uroot password '123456'  

[root@host ~]# mysql -uroot    //设置好密码的话,再次登陆要加-p,不然报错
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

[root@host ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.
mysql>
注意: -p后面可以直接带密码,不用加空格,例如 -p'123456',引号可以不加,但是密码如果是带有特殊符号的,就必须加引号,所以最好习惯加引号
也可以在Enter后再输入密码,这样会不容易泄漏密码,更安全。

1.3 更改密码

  • 知道原密码的情况下
[root@host ~]# mysqladmin -uroot -p'123456' password '1234567'

[root@host ~]# mysql -uroot -p'1234567'
Welcome to the MySQL monitor.
mysql>
  • 不知道原密码的情况下
  1. 编辑mysql配置文件,添加skip-grant
[root@host ~]# vim /etc/my.cnf

[mysqld]
skip-grant    //添加这一行,表示忽略授权
datadir=/data/mysql
socket=/tmp/mysql.sock
……
  1. 重启mysql服务
[root@host ~]# /etc/init.d/mysqld restart
Shutting down MySQL... SUCCESS! 
Starting MySQL..................... SUCCESS! 
#重启之后,登陆MySQL就不需要密码了
  1. 直接登陆MySQL,设置密码
[root@host ~]# mysql -uroot
Welcome to the MySQL monitor.  
mysql> use mysql;      //切换到mysql库
Database changed

mysql> select * from user\G;    //查看用户的表信息(密码,授权等等)
(/G: 使输出信息有序显示,不然显示内容会很乱  )

mysql> select password from user;   //查看用户密码,显示结果Wie加密字符串!  
mysql> update user set password=password('123456') where user='root';    //用123456代替原密码(将密码设置为123456)
Query OK, 4 rows affected (0.11 sec)
Rows matched: 4  Changed: 4  Warnings: 0
mysql> quit
Bye

2. 连接mysql

2.1 远程连接:使用IP&port

[root@host ~]# mysql -uroot -p123456 -h127.0.0.1 -P3306   //-p=password   -h=host  -P=port
Welcome to the MySQL monitor.
mysql> quit
Bye

2.2 本机连接:使用socket

[root@host ~]# mysql -uroot -p123456 -S/tmp/mysql.sock   //-S 制定socket
#只适用于本机连接,等同于“mysql -uroot -p123456”
Welcome to the MySQL monitor.
mysql> quit
Bye

2.3 显示数据库信息,一般用于脚本中

[root@host ~]# mysql -uroot -p'123456' -e "show databases"  //-e 可以执行一些命令
Warning: Using a password on the command line interface can be insecure.
+--------------------+
| Database          |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test              |
+--------------------+

3. mysql常用命令

3.1 查看库的信息

mysql>

查询库 show databases;
切换库 use mysql;

3.2 这些命令需要在切换库之后执行

# mysql> use mysql

查看库里的表 show tables;
查看表里的字段 desc tb_name;
查看建表语句 show create table tb_name\G;
查看当前用户 select user();
查看当前使用的数据库 select databsase();