为MySQL中root用户设置密码

时间:2021-03-15 16:19:05

使用SET PASSWORD语句修改root密码:
shell> mysql -u root
mysql> SET PASSWORD FOR ''@'localhost' = PASSWORD('newpwd');
mysql> SET PASSWORD FOR ''@'host_name' = PASSWORD('newpwd');

设置匿名账户密码:
shell> mysql -u root
mysql> UPDATE mysql.user SET Password = PASSWORD('newpwd')
-> WHERE User = '';
mysql> FLUSH PRIVILEGES;

删除匿名账户:
shell> mysql -u root
mysql> DELETE FROM mysql.user WHERE User = '';
mysql> FLUSH PRIVILEGES;

使用mysqladmin工具修改密码:
shell> mysqladmin -u root password "newpwd"
shell> mysqladmin -u root -h host_name password "newpwd"

可以使用UPDATE直接修改user表:
shell> mysql -u root
mysql> UPDATE mysql.user SET Password = PASSWORD('newpwd')
-> WHERE User = 'root';
mysql> FLUSH PRIVILEGES;

忘记MySQL密码,找回方法:
$ kill `cat /tmp/mysql.pid`
创建文本文件,并将下述命令放在~/mysql-init文件内的1行上:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPassword');
用此方法启动:
mysqld_safe --init-file=~/mysql-init &