0%

windows-mysql-forget-root-password

Windows下忘记mysql的root密码(–skip-grant-tables)

首先,需要注意my.ini的位置,一般,my.ini会在两个地方,第一个位置是在安装mysql服务的位置(举例,
C:/Program Files/MySQL/MySQL Server X.Y),第二个位置地方则是Data的同级目录下(举例,
datadir的路径是C:/ProgramData/MySQL/MySQL Server 8.0/Data,则my.ini的位置是
C:/ProgramData/MySQL/MySQL Server 8.0/my.ini)。

如果my.ini不在第一个位置,则在后面需要使用–defaults-file

跳过grant tables

在windows上使用--skip-grant-tables的同时必须同时使用--shared-memory--named-pipe
的一个。

mysql –defaults-file=”C:\ProgramData\MySQL\MySQL Server 8.0\my.ini”
–console –skip-grant-tables –shared-memory

mysql –defaults-file=”C:\ProgramData\MySQL\MySQL Server 8.0\my.ini”
–console –skip-grant-tables –named-pipe

说明

  • 像上面说的一样,如果my.ini在mysql服务的安装位置上,则可以省略--defaults-file
  • --console -用于设置默认错误日志目标为控制台,有利于与观察服务运行状态。
  • --skip-grant-tables - 跳过grant tables,这是必须的。
  • --shared-memory--named-pipe - 二选一,注意,这两个协议只在windows上有效。
    • 另外提一句,在linux下是socket(不是特指TCP/IPTCP/IP是默认系统通用)

注意

1
2
--skip-grant-tables将跳过grant tables,同时拒绝远程访问,并且给予任何人
unrestricted access to all databases(不受限制地访问所有数据库)。

另一种方法,修改my.ini

通过修改my.ini同样可以达到这种方法,通过在mysqld下添加skip-grant-tables
shared-memory(或named-pipe)同样可以达到上面的效果,同时,依然要注意my.ini
的位置,这也是网上有人说修改my.ini的原因,因为并没有正确加载。

mysql连接

这里比较简单,基本可以一笔带过,直接在terminal中键入mysql就可以直接连接到数据库。

注意,如果使用了--named-pipe,在需要使用mysql --protocol=pipe,protocol的默认
是memory(–shared-memory)

数据库操作

刷入权限

首先,接下来的操作需要权限,所以需要FLUSH PRIVILEGES获取权限

1
MariaDB [(none)] > FLUSH PRIVILEGES;

官方文档对于权限的描述如下

1
2
3
4
5
To cause a server started with --skip-grant-tables to load the grant tables at runtime, perform a privilege-flushing operation, which can be done in these ways:

Issue a MySQL FLUSH PRIVILEGES statement after connecting to the server.

Execute a mysqladmin flush-privileges or mysqladmin reload command from the command line.

修改密码

这一个就是常规操作,简略地提供一种方法

1
MariaDB [(none)] > ALTER USER 'root'@'localhost' IDENTIFIED BY '<your_passcode>';