1
0

MySQL Connectorを使いDBに接続するのに苦戦した話.

Last updated at Posted at 2023-12-24

概要

  • Pythonのライブラリにある mysql.connectorを使って, Kubernetes上で動作しているpodに接続しようとした.
  • 接続テストした際, Authentication plugin 'caching_sha2_password' is not supportedとの表示があった.
  • 改善策として, 接続設定(データベースのホスト名, port番号等)の指定にauth_pluginの記述と, MySQLのPodのパスワードの形式をmysql_native_passwordの指定を行った.

バージョン, 構成

MySQL: v8.0.35
k3s環境にMySQLのPodを立て, そのPodに接続

原因

MySQL8.0以上のインストールまたはアップグレード後に作成された新しいアカウントのパスワードの認証方式は, mysql_native_passwordの認証プラグインではなく, caching_sha2_passwordに置き換えられていた.
実際にデータベースサーバーにアクセスしようとしていたユーザーはcaching ~ の形式になっていたため, mysql.connectorで接続した際, 認証できずプログラムが実行できなかった.

解決策

MySQLに登録しているDB用ユーザーパスワードの認証形式をmysql_native_passwordに変更する.


現在の状況を確認する.

mysql -u root -p

パスワードの認証方式の確認コマンド.

MySQL [(none)]> select user,plugin from mysql.user;
+------------------+-----------------------+
| user             | plugin                |
+------------------+-----------------------+
| cdsl             | caching_sha2_password |
| root             | caching_sha2_password |
| mysql.infoschema | caching_sha2_password |
| mysql.session    | caching_sha2_password |
| mysql.sys        | caching_sha2_password |
| root             | caching_sha2_password |
+------------------+-----------------------+

今回はcdslというユーザーを使って, mysqlconnectorに接続する. そのため, 該当ユーザーのパスワードの認証方式を変える必要がある.
ユーザーとパスワードに関しては適宜設定された値に置き換えてください.

alter user 'cdsl(your user)'@'%' identified with mysql_native_password by '(your password)';

コマンド入力後, Query OKが表示されていたら, 認証方式が変更されている.

実際に, 認証方式が変更されたかどうかの確認を行う.

MySQL [(none)]> select user,plugin from mysql.user;
+------------------+-----------------------+
| user             | plugin                |
+------------------+-----------------------+
| cdsl             | mysql_native_password |
| root             | caching_sha2_password |
| mysql.infoschema | caching_sha2_password |
| mysql.session    | caching_sha2_password |
| mysql.sys        | caching_sha2_password |
| root             | caching_sha2_password |
+------------------+-----------------------+

変更されていることが確認できる.


最後に, Pythonに記述したデータベースの接続情報のコードに, パスワード認証方式(auth_plugin)をmysql_native_passwordを利用する旨を記載する.

db_config = {
    'host': '(データベースのアドレス)',
    'port': (データベース上で設定したポートの指定),
    'user': '(Your Name)',
    'password': '(Your Password)',
    'database': '(Your Database)',
    'auth_plugin': 'mysql_native_password',
}

これにて完了!!! お疲れ様でした!

最後に

ここまでお読みいただいて, ありがとうございました!

この情報が参考になれば幸いです.
それでは!

1
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
1
0