Método detallado de MySQL Quick Check para restablecer la contraseña de MySQL

Comprobación rápida de MySQL

Debido a que a menudo olvido algunas declaraciones, palabras clave, operaciones, etc. de MySQL en mi trabajo y estudio diario, recientemente me tomé un tiempo para escribir el siguiente contenido sobre MySQL. es como un diccionario


Este artículo


Operadores de tipo de datos
Funciones comúnmente utilizadas
Integridad de datos
Operaciones básicas de la base de datos Operaciones
en la propia tabla Operaciones
sobre datos en la tabla Subconsultas Conexiones de
múltiples tablas Vistas de índice Preprocesamiento de sentencias SQL Funciones personalizadas y procedimientos almacenados Programación en MySQL






restablecer contraseña de mysql


consejo: principalmente para mysql8

  1. Si todavía tienes la contraseña original, puedes usar mysqladmin para cambiar la contraseña (esto es más fácil)
# 命令
mysqladmin -h主机 -u用户名 -p 原密码 password 新密码
# 如果mysql就安装在自己的机器上,可以不写"-h"选项;
# 如果是新安装的mysql(没有设置过密码)"-p"选项后面不用写原密码,
# 回车后会提示"Enter password",不用输入,直接回车

# 将root用户的密码由原来的admin修改为root
>> mysqladmin -uroot -padmin password root
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
# 这个警告是说密码是明文发送到mysql服务器的,建议使用ssl连接,不用理会

Si el método anterior no funciona o ha olvidado la contraseña original, debe utilizar el siguiente método.
De hecho, mysqladmin combinado con mysqld_safe también puede resolver el problema de restablecer la contraseña después de olvidarla, si está interesado, puede buscar

  1. Utilice mysql para iniciar sesión sin ningún parámetro
>mysql
ERROR 1045 (28000): Access denied for user 'cracal'@'localhost' (using password: NO)

Si ocurre el error anterior, busque el archivo de configuración de MySQL y agregue " skip-grant-tables " en [mysqld]

  • Windows puede encontrar el servicio mysql haciendo clic derecho en esta computadora- > Administrar- > Servicios y aplicaciones- > Servicios . Si no cambió el nombre durante la instalación, generalmente se llamará Mysqld*.*. Haga doble clic en el archivo ejecutable. en el cuadro de diálogo emergente, busque la ruta de my.ini en la ruta , cópielo y ábralo, se requieren derechos de administrador para cambiar el archivo.
  • Ubuntu es generalmente /etc/mysql/mysql.conf.d/mysqld.cnf.
  • Centos es generalmente /etc/my.cnf.d/mysql-server.cnf.
  • Me preguntaste por qué Linux no es /etc/my.cnf o /etc/mysql/my.cnf, porque no puedo iniciar el servicio mysql después de modificarlo. También se puede utilizar si modifica uno de estos dos para lograr el propósito.
    Nota: Después de agregar skip-grant-tables, debe reiniciar el servicio mysql:
    • Windows se puede reiniciar visualmente en la interfaz de servicio abierta arriba (o reiniciar con el comando net)
    • Linux usa el comando systemctl restart mysql.service para reiniciar
...
[mysqld]
skip-grant-tables
...
  1. Inicie sesión y seleccione mysql
>>mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.23-0ubuntu0.20.04.1 (Ubuntu)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

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
  1. Borrar contraseña
    Para facilitar la descripción y el funcionamiento, la contraseña se borrará independientemente de si la cuenta raíz anterior tiene una contraseña establecida o no.
mysql> update user set authentication_string="" where user="root";
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

  1. restablecer la contraseña
alter user '账号'@'主机' identified by '密码';
# 例 将localhost主机的root账号设置密码为root
mysql> alter user 'root'@'localhost' identified by 'root';

4.1 Nota: Si se informa el siguiente error,

mysql> alter user 'root'@'localhost' identified by 'root';
ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement

Los privilegios se pueden actualizar usando privilegios de vaciado

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

Luego continúe ejecutando alter...

4.2 Si se informa el siguiente error

mysql> alter user 'root'@'localhost' identified by 'root';
ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded

Luego ejecute la siguiente declaración

update  mysql.user set  `plugin`='mysql_native_password'  WHERE `user`='root' AND `host`='localhost';
# where子句可以不加

Luego use quit para salir de mysql, luego reinicie el servicio mysql y luego use el comando mysql sin ningún parámetro para iniciar sesión; seleccione la base de datos mysql y continúe ejecutando la instrucción alter.
Nota: Si cambia la contraseña después de reiniciar, es posible que aún reciba el error 4.1, que se puede modificar de acuerdo con la solución 4.1.

# 登陆mysql
>>mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 8.0.23-0ubuntu0.20.04.1 (Ubuntu)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
# 选择mysql数据库
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> alter user 'root'@'localhost' identified by 'root';
Query OK, 0 rows affected (0.01 sec)

En términos generales, la contraseña se puede cambiar una vez completadas estas operaciones. Si encuentra otros errores, puede buscar soluciones según el mensaje de error.

  1. Salga de mysql, elimine skip-grant-tables (si se agregó antes), reinicie el servicio mysql e inicie sesión con la cuenta raíz para realizar la prueba.
# 重启服务
>> sudo systemctl restart mysql.service 
# 登陆mysql
>> mysql -uroot -p
Enter password: # 键入密码
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.23-0ubuntu0.20.04.1 (Ubuntu)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

¡eso es todo!


Si usamostrar bases de datosLa declaración informa el siguiente error:

mysql> show databases;
ERROR 1449 (HY000): The user specified as a definer ('mysql.infoschema'@'localhost') does not exist

Según el informe de error, podemos saber que el usuario "mysql.infoschema" no existe, por lo que debemos crear el usuario manualmente.

# 创建用户
# 原型:
create user '用户名'@'主机名' identified by '密码';
# 例子
mysql> create user 'mysql.infoschema'@'%' identified by 'root';
Query OK, 0 rows affected (0.01 sec)

# 授权
# 原型:
grant all privileges on 数据库名.表名 to '用户名'@'主机名';
# 例子
mysql> grant all privileges on *.* to 'mysql.infoschema'@'%';
Query OK, 0 rows affected (0.01 sec)

# 刷新
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

# 测试
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

Supongo que te gusta

Origin blog.csdn.net/weixin_45345384/article/details/116808261
Recomendado
Clasificación