MySQLにパスワードを入力せずに接続する方法

こんにちは、さるまりんです。

今回はMySQLの小ネタです。

ローカルに構築したMySQLデータベースsalu_dbにユーザーsalu_usrmysqlクライアントプログラムを使って接続しようとするとこんなふうになります。

$ mysql -D salu_db -u salu_usr
ERROR 1045 (28000): Access denied for user 'salu_usr'@'localhost' (using password: NO)

-pをつけるとパスワード入力を促されて、正しいパスワードを入力するとつながります。

$ mysql -D salu_db -u salu_usr -p
Enter password: 
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 17140
Server version: 5.6.51 MySQL Community Server (GPL)

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

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>

面倒です。(面倒とか言ってはいけないのかもしれないですね。。)

~/.my.cnfを作成し、下のような内容を入力します。

[mysql]
user=salu_usr
password=[接続パスワード]
database=salu_db

ユーザー、パスワード、接続するDBを指定しています。

これを設定しておくとオプション等なしで指定のユーザー、データベースに接続することができます。

$ mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 17142
Server version: 5.6.51 MySQL Community Server (GPL)

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

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>

セキュリティ上どうなのか疑問は残りますが、せめてchmod 600 .my.cnfくらいして、自分しか見れないようにしておくのもいいかもしれないです。

読んでくださってありがとうございました。

それではまた!