忽然忘記 MySql 的 root 密碼,或者 CentOS 剛裝好的時候在 root 密碼尚未設定的狀態下都可以透過以下方法來修改 root 密碼。
MySql 無法使用 root 連線,先來看看發生什麼事情:
[root@centos ~]# mysql -u root -p Enter password: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) [root@centos ~]# mysqladmin -u root -p password Enter password: mysqladmin: connect to server at 'localhost' failed error: 'Access denied for user 'root'@'localhost' (using password: NO)' [root@centos ~]#
既然 mysqladmin 也改不了密碼了,那我們只好重新啟動 mysql 並且進入安全模式,這時候就可以不用 root 密碼登入了。
[root@centos ~]# service mysqld stop 正在停止 MySQL: [ 確定 ] [root@centos ~]# mysqld_safe --user=mysql --skip-grant-tables --skip-networking & [1] 27349 Starting mysqld daemon with databases from /var/lib/mysql [root@centos ~]# mysql -u root mysql Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.0.77 Source distribution Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> UPDATE user SET Password=PASSWORD('iamroot') where USER='root'; Query OK, 3 rows affected (0.02 sec) Rows matched: 3 Changed: 3 Warnings: 0 mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) mysql> quit Bye [root@centos ~]#
重新將 MySql 啟動在正常模式,並且測試新的 root 密碼是否能夠使用。
[root@centos ~]# service mysqld restart STOPPING server from pid file /var/run/mysqld/mysqld.pid 101220 16:58:31 mysqld ended 正在停止 MySQL: [ 確定 ] 正在啟動 MySQL: [ 確定 ] [1]+ Done mysqld_safe --user=mysql --skip-grant-tables --skip-networking [root@centos ~]# mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.0.77 Source distribution Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql>
搞定了,以後就看這一招了.......!?