1.第一次安装时没有密码:如何设置默认密码
在linux上安装了mysql,刚安装时没有密码 然后我通过update user set authentication_string='密码' where user='root';去修改密码 会提示如下:
执行语句成功,但是受影响的行为0
实际上第一次没有设置密码 需要通过mysqladmin -u root password '密码' 这个命令来设置密码,设置好了之后如果需要修改密码才能够通过update user set authentication_string='密码' where user='root';去修改
2.忘记密码时如何修改密码
如下 打开文件my.cnf --> vim /etc/my.cnf
然后在该文件的[mysqld]下面添加 skip-grant-tables(如果文件里面没有[mysqld] 就自己添加一个即可) 然后重启mysql服务 就可以直接不需要密码进入mysql了,然后看通过update user set authentication_string='密码' where user='root';修改密码
authentication_string字段好像是mysql5.7以上才有的,如果这个字段找不到就用password字段如:update user set password='密码' where user='root';
以上方法我尝试过几次,有时候行,有时候不行,如果不行还可以尝试如下方法(原文链接:https://zhuanlan.zhihu.com/p/141778941):
首先还是在vim /etc/my.cnf 下添加skip-grant-tables 让登录mysql的时候跳过验证
然后进入mysql选择 mysql数据库(use mysql) 然后修改user表的authentication_string字段为空 (即把密码置空)
update user set authentication_string = '' where user = 'root';
然后去除免密码登陆(修改mysql配置,删掉步骤2的语句 skip-grant-tables) 再重启服务
重启服务 service mysqld restart
进入数据库 修改密码
进入数据库
mysql -u root -p //提示输入密码时直接敲回车,刚刚已经将密码置空了
修改密码
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '在这里输入你的密码';
ERROR 1396 (HY000): Operation ALTER USER failed for 'root'@'%
我这里提示ERROR 查阅了另外一篇文章说是把%改为localhost即可,即:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123';
然后就成功了,重启服务 OK