安装MySQL
通过root用户或具有sudo权限的用户使用CentOS软件包管理器来安装MySQL服务器
sudo dnf install @mysql
启停MySQL服务
启动mysql服务:
sudo systemctl start mysqld
停止mysql服务:
sudo systemctl stop mysqld
重启mysql服务:
sudo systemctl restart mysqld
检查mysql服务运行状态:
sudo systemctl status mysqld
使mysql服务在服务器启动时自动启动:
sudo systemctl enable mysqld
停止mysql服务在服务器启动时自动启动:
sudo systemctl disable mysqld
用户管理
首次登陆前设置root密码
# 设置mysql root账户密码为rootpasswordmysqladmin -u root password rootpassword
更改root用户密码
# 更改root账户密码为newrootpasswordmysqladmin -u root password newrootpassword -p# 之后提示输入旧密码
登录mysql
mysql -h localhost -u root -p
新建用户
新建用户本质上是将新用户的字段insert到mysql.user table中,因此可以通过select User,Host from mysql.user来查询所有用户。
create user 'username'@'host' identified by 'userpassword';
host:指定该用户在哪个主机上可以登陆,
- 如果是ip地址则只有指定的ip地址能登录该用户。
- 如果是本地用户可用
localhost。 - 如果想让该用户可以从任意主机登陆(本地或远程),可以使用通配符
%。默认值为%。
用root用户登录mysql以后,新建user用户,用户密码为userpassword:
create user 'user'@'localhost' identified by 'userpassword';create user 'user'@'192.168.111.111' identified by 'userpassword';create user 'user'@'%' identified by 'userpassword';create user 'user' identified by 'userpassword';create user 'user'@'%' identified by 'userpassword';create user 'user'@'%' identified by '';create user 'user'@'%'; # 同上不要密码
密码可以为空,如果为空则该用户可以不需要密码登陆服务器。
更改用户密码
set password for 'username'@'host' = 'newpassword';set password = 'newpassword'; # 更改当前用户密码# 例子set password for 'user'@'%' = '123456'
删除用户
drop user 'username'@'host';
用户授权
# 格式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命令创建用户或者给其它用户授权。
例子:
grant all privileges on *.* to 'user'@'%';grant all privileges on db1.table1 to 'user'@'localhost';grant select, insert on *.* to 'user'@'%';grant all privileges on *.* to 'user'@'%' with grant option;
# 授权生效flush privileges;# 查看权限show grants;# 查看某个用户的权限show grants for 'user'@'%';# 删除权限revoke privileges on dbName.tableName from 'username'@'host';# privileges - all, select, insert, update, etc.
远程服务器端口开放
如果mysql服务布置在远程服务器上,如阿里云ECS。需要打开远程服务器的3306端口。
