安装MySQL

通过root用户或具有sudo权限的用户使用CentOS软件包管理器来安装MySQL服务器

  1. sudo dnf install @mysql

启停MySQL服务

启动mysql服务:

  1. sudo systemctl start mysqld

停止mysql服务:

  1. sudo systemctl stop mysqld

重启mysql服务:

  1. sudo systemctl restart mysqld

检查mysql服务运行状态:

  1. sudo systemctl status mysqld

使mysql服务在服务器启动时自动启动:

  1. sudo systemctl enable mysqld

停止mysql服务在服务器启动时自动启动:

  1. sudo systemctl disable mysqld

用户管理

首次登陆前设置root密码

  1. # 设置mysql root账户密码为rootpassword
  2. mysqladmin -u root password rootpassword

更改root用户密码

  1. # 更改root账户密码为newrootpassword
  2. mysqladmin -u root password newrootpassword -p
  3. # 之后提示输入旧密码

登录mysql

  1. mysql -h localhost -u root -p

新建用户

新建用户本质上是将新用户的字段insert到mysql.user table中,因此可以通过select User,Host from mysql.user来查询所有用户。

  1. create user 'username'@'host' identified by 'userpassword';

host:指定该用户在哪个主机上可以登陆,

  • 如果是ip地址则只有指定的ip地址能登录该用户。
  • 如果是本地用户可用localhost
  • 如果想让该用户可以从任意主机登陆(本地或远程),可以使用通配符%。默认值为%

用root用户登录mysql以后,新建user用户,用户密码为userpassword:

  1. create user 'user'@'localhost' identified by 'userpassword';
  2. create user 'user'@'192.168.111.111' identified by 'userpassword';
  3. create user 'user'@'%' identified by 'userpassword';
  4. create user 'user' identified by 'userpassword';
  5. create user 'user'@'%' identified by 'userpassword';
  6. create user 'user'@'%' identified by '';
  7. create user 'user'@'%'; # 同上不要密码

密码可以为空,如果为空则该用户可以不需要密码登陆服务器。

更改用户密码

  1. set password for 'username'@'host' = 'newpassword';
  2. set password = 'newpassword'; # 更改当前用户密码
  3. # 例子
  4. set password for 'user'@'%' = '123456'

删除用户

  1. drop user 'username'@'host';

用户授权

  1. # 格式
  2. grant privilegesCode on dbName.tableName to username@host [with grant option];

privilegesCode表示授予的权限类型,常用的有以下几种类型:

  • all privileges:所有权限。
  • select:读取权限。
  • delete:删除权限。
  • update:更新权限。
  • create:创建权限。
  • drop:删除数据库、数据表权限。

dbName.tableName表示授予权限的具体库或表,常用的有以下几种选项:

  • *.*:授予该数据库服务器所有数据库的权限。
  • dbName.*:授予dbName数据库所有表的权限。
  • dbName.tableName:授予数据库dbName中tableName表的权限。

username@host表示授予的用户以及允许该用户登录的IP地址。其中host有以下几种类型:

  • localhost:只允许该用户在本地登录,不能远程登录。
  • %:允许远程登录。
  • 192.168.52.32:具体的IP表示只允许该用户从特定IP登录。

with grant option表示该用户可以将自己拥有的权限授权给别人。注意:经常有人在创建操作用户的时候不指定with grant option选项导致后来该用户不能使用grant命令创建用户或者给其它用户授权。

例子:

  1. grant all privileges on *.* to 'user'@'%';
  2. grant all privileges on db1.table1 to 'user'@'localhost';
  3. grant select, insert on *.* to 'user'@'%';
  4. grant all privileges on *.* to 'user'@'%' with grant option;
  1. # 授权生效
  2. flush privileges;
  3. # 查看权限
  4. show grants;
  5. # 查看某个用户的权限
  6. show grants for 'user'@'%';
  7. # 删除权限
  8. revoke privileges on dbName.tableName from 'username'@'host';
  9. # privileges - all, select, insert, update, etc.

远程服务器端口开放

如果mysql服务布置在远程服务器上,如阿里云ECS。需要打开远程服务器的3306端口。