0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】UbuntuでインストールしたMySQLのデータを初期化するやり方

Last updated at Posted at 2025-04-23

実行する前に必ず確認してください

  • この記事のコマンドはAIに聞いて、実行できるか試していますが、バージョンの違いなどにより、実行できなくなっている可能性がありますので、ご了承ください
  • MySQLについて詳しくは、そこまで知らないため、質問してもお答えできない場合があります
  • 任意ですがバックアップをおこなってください
  • 実行する場合は自己責任でお願いします

動作環境

  • OS: Ubuntu 22.04.3 LTS
  • MySQL: Ver 8.0.41

下記のコマンドで、OSとMySQLのバージョンを確認できると思います。(MySQLをインストールしている時)

mysql --version

データベースの削除・ディレクトリの初期化

起動している場合は、いったん起動停止をしましょう。

sudo systemctl stop mysql

データベースのフォルダ権限の書き換え(念のため)

sudo chown -R $USER:$USER /var/lib/mysql/

データベースのフォルダを削除

sudo rm -rf /var/lib/mysql/

データベースのフォルダの中身がなくなったか確認

ls -l /var/lib/mysql/

ディレクトリの初期化

sudo /usr/sbin/mysqld --user=mysql --initialize

一度に実行したい人向け

sudo systemctl stop mysql
sudo chown -R $USER:$USER /var/lib/mysql/
sudo rm -rf /var/lib/mysql/
sudo /usr/sbin/mysqld --user=mysql --initialize

このようなログが最後に出れば成功です

terminalのlog.
XXXX-XX-XXTXX:XX:XX.XXXXXXZ 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: ${Password}

${Password}は一時パスワードです。再インストール時に必要となりますので、メモしておいてください。

起動確認

MySQLの起動

sudo systemctl start mysql

MySQLが起動しているか確認
active (running)と出ていれば、起動成功です。

sudo systemctl status mysql

MySQLへの接続

mysql -u root -p

実行すると、

terminalのlog.
Enter password: 

と聞かれるので、先ほど取得した一時パスワードでログインしましょう。

成功したらMySQLのコンソールが出ると思います。
下記のようなものです。
このあとは「MySQLのコンソール」のことを「SQL画面」と呼びます

SQL画面.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.41-0ubuntu0.22.04.1

Copyright (c) 2000, 2025, 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> 

下記の「新しいパスワード」に自分が使う、安全なパスワードを入れて、SQL画面で実行してください。

ALTER USER 'root'@'localhost' IDENTIFIED BY '新しいパスワード';

「Query OK」が表示されれば変更できたことになります。

これにて、MySQLを初期化の手順を終わります。
おつかれさまでした。

SQL画面の閉じ方は下のコマンドを実行することで終了することができます。

exit

参考

Gemini2.0 Flash に何度質問して、実行を何回も試した上で、正確性を試した上で記事を載せています。
https://gemini.google.com/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?