mysql5.7常见问题及解决方案
文章目录
1.常见命令
# root密码登录
mysql -u root -p
# 指定ip地址密码登录
mysql -u root -h 192.168.1.1 -p
# 查询用户和主机(以root身份)
use mysql;
select user,host from user;
1.远程主机无法访问
1.1一般情况:修改host,然后问题解决
- bug:Host XXX is not allowed to connect to this MySQL server
修改host
# 以root身份登录
use mysql;
# 查看host的状态
select host from user where user='root';
# 将Host设置为通配符%
update user set host = '%' where user ='root';
# 刷新权限即可
flush privileges;
参考地址:https://blog.csdn.net/h985161183/article/details/82218710
1.2特殊情况:修改host仍然未解决
- 1.3306端口冲突,本人实际遇到的就是这中情况
实际遇到问题的环境为windows,解决方法:
# 打开命令行,查看3306端口
netstat -ano | findstr "3306"
# 查看占用端口的程序
tasklist | findstr "9158"
# 发现有两个mysql进程都占据了3306端口;
# 可使用快捷键win+r,输入`services.msc`,在服务中关闭一个mysql或者直接使用命令杀掉一个进程(如杀掉9158进程)
taskkill /pid 9158
# 然后问题解决
2.忘记密码
2.1windows环境
- 1.在mysql安装目录下,找到my.ini文件,打开文件,在
[mysqld]
后面任意行,加入skip-grant-tables
; - 2.重启MySQL:使用快捷键win+r打开运行,输入
services.msc
,回车打开服务,找到mysql服务,然后右击选择重启MySQL; - 3.打开cmd命令行,输入
mysql -u root -p
,直接登录mysql; - 4.修改root密码;
use mysql;
# 旧的修改语句
update user set password=password("你的新密码") where user="root";
# 使用旧的修改语句如果报错:Unknown column ‘password’ in ‘field list’,则使用下面语句:
# 注:新版本的mysql对密码有要求,具体见附录
update mysql.user set authentication_string=password('root') where user='root' ;
# 刷新权限
flush privileges;
- 5.再次打开my.ini文件,删除
skip-grant-tables
,然后重启mysql服务。
2.2linux环境
- 1.打开my.cnf文件,
vi /etc/my.cnf
,[mysqld]
后面任意行,加入skip-grant-tables
,用来跳过密码验证的过程; - 2.使用/etc/init.d/mysql restart(或可能需要使用/etc/init.d/mysqld restart)重启mysql服务;
- 3.登录mysql,并修改密码,具体过程与windows环境一致;
- 4.修改完成后再打开my.cnf文件,删除
skip-grant-tables
,然后重启mysql服务。
参考地址:https://blog.csdn.net/yunfeng482/article/details/89220327
3.添加用户并授权
# 以root用户登录mysql
mysql -u root -p
use mysql;
# 添加只能本地访问的新用户
create user 'user'@'localhost' identified by 'user!123456';
# 添加外网ip可以访问的新用户
create user 'user'@'%' identified by 'user!123456';
# 用户创建完成后需要授权
flush privileges;
# 基于业务的授权
grant all privileges on dbname.* to user@'%' identified by 'user!123456';
grant all privileges on dbname.* to user@'%' identified by 'user!123456' with grant option;
# 基于管理员的授权(两者差别见参考地址1)
grant all privileges on *.* to user@'%' identified by 'user!123456';
grant all privileges on *.* to user@'%' identified by 'user!123456' with grant option;
# 授权后,刷新权限
flush privileges;
参考地址:1.同样是MySQL的all privileges有啥不同?
附录
1.mysql密码策略
validate_password_length:密码最小长度,参数默认为8,它有最小值的限制,最小值为:validate_password_number_count + validate_password_special_char_count + (2 * validate_password_mixed_case_count)
validate_password_mixed_case_count:密码至少要包含的1个小写字母个数或大写字母。
validate_password_number_count:密码至少要包含的1个数字。
validate_password_special_char_count:密码至少要包含1个特殊字符数。
参考网址:
1.Mysql密码策略