MySQL修改root密码后依然无法登陆的原因分析
打开博客,突然发现博客打不开了,报错,数据库连接错误。
恩,一定是密码错误,登陆ssh,敲命令:mysql -u root -p
然后输入密码,咦,1045禁止登陆,再次输入,还是1045错误。
好吧,也许是root密码忘了。
修改密码。
# vi /etc/my.cnf
在[mysqld]的段中加上一句:skip-grant-tables
例如:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
skip-grant-tables
保存并且退出vi。
3.重新启动mysqld
# /etc/init.d/mysqld restart
Stopping MySQL: [ OK ]
Starting MySQL: [ OK ]
4.登录并修改MySQL的root密码
# /usr/bin/mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 3.23.56
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.
mysql> USE mysql ;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> UPDATE user SET Password = password ( ‘new-password’ ) WHERE User = ‘root’ ;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 2 Changed: 0 Warnings: 0
mysql> flush privileges ;
Query OK, 0 rows affected (0.01 sec)
mysql> quit
Bye
5.将MySQL的登录设置修改回来
# vi /etc/my.cnf
将刚才在[mysqld]的段中加上的skip-grant-tables删除
保存并且退出vi。
6.重新启动mysqld
# /etc/init.d/mysqld restart
Stopping MySQL: [ OK ]
Starting MySQL: [ OK ]
修改完了,再次使用mysql -u root -p,咦,依然不对。我明明已经改过了。
再改,还是不对。
突然,我发现,1045报错句子中:
ERROR 1045 (28000): Access denied for user ‘mysql’@’localhost’ (using password: YES)
有一个localhost,莫非是这个问题?
再次跳过MySQL密码检查,重启,不用密码登录后,选择数据库,然后执行:
select * from user;
呜呼!原来root的Host是127.0.0.1!我猜一定是这个问题。然后使用更新语句把Host改为了locahost,果然好了!
但是,为什么两个不一样呢?搜索了一下,有的说两个地址还是不能通用的。最直接的办法是:
update user set Host=’%’ where user=’root’;
这样,%表示所有包括localhost和127.0.0.1或者其他,就能保证不论程序中配置的是127.0.0.1还是localhost都能顺利连接。