MySQL数据库修改密码

38 阅读2分钟

背景

现在很多修改MySQL数据库密码的帖子比较老,已经不适用于MySQL 8.X的版本。 网上不少修改数据库的版本,但是对于MySQL 8.X不适用。

正文

网上现在修改数据数据库密码有一下几个方案。

1、方案一

使用set命令修改MySQL数据库密码,命令如下

1、mysql -u root -p ;登录 MySQL
2\set password for username @localhost = password(newpwd);设置新密码。

在mysql8.X以后会报错,错误如下:

ERROR 1064 (42000): You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to use near 'password('123456')' at line 1
翻译一下就是;
错误106442000):您的SQL语法有错误;查看与MySQL服务器版本对应的手册,了解在第1行的“password(123456)”附近使用的正确语法
使用的命令和MySQL的版本不对应

方案二

使用 mysqladmin 命令修改数据库密码 命令如下

1、mysql -u root -p ;登录 MySQL
2、mysqladmin -uroot -p newpwd password oldpwd;设置新密码。

8.x版本会报错:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that 
corresponds to your MySQL server version for the right syntax to
 use near 'mysqladmin -uroot -p123456 password Cfca@1234!' at line 1

方案三

命令在 MySQL 5.7.6之后的版本中可以使用,8.0之后的版本不适用,虽然也会有同样的表和字段。

1、mysql -u root -p ;登录 MySQL
2、use mysql;连接权限数据库。
3、update mysql.user set authentication_string=password('123456') 
where user='root' and Host ='localhost';设置新密码。
4、flush privileges; 刷新权限使得修改生效。
5、quit;退出

报错如下;
ERROR 1064 (42000): You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to 
use near '('123456') where user='root' and Host ='localhost'' at line 1

方案四

这个方案是在MySQL8.0以后可用的

1、mysql -u root -p;登录 MySQL
2ALTER USER 'username'@'localhost' IDENTIFIED BY 'new_password'; 设置新密码。
3、FLUSH PRIVILEGES;刷新权限使得修改生效: