3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mysql-connector-pythonでMySQLに接続試行すると「SSL connection error: SSL_CTX_set_tmp_dh failed」エラーで接続できない

Last updated at Posted at 2020-01-11

はじめに

Pythonの「mysql-connector-python」ライブラリを使って、Dockerイメージから起動したMySQLサーバに接続を試みたところ、「SSL connection error: SSL_CTX_set_tmp_dh failed」エラーが発生し、MySQLに接続できない問題が発生しました。

test.py
import mysql.connector

conn = mysql.connector.connect(
    host='127.0.0.1',
    port='3306',
    user='user',
    password='password', 
    database='sample_db'
)
cursor = conn.cursor()

↓ 実行後

エラーメッセージ
Traceback (most recent call last):
  File "/Users/user1/opt/anaconda3/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 200, in _open_connection
    self._cmysql.connect(**cnx_kwargs)
_mysql_connector.MySQLInterfaceError: SSL connection error: SSL_CTX_set_tmp_dh failed

# // 省略

こちら一旦、接続できる状態になったので備忘録として残します。

実行環境

■クライアント

  • macOS Catalina 10.15.2
  • Anaconda3に含まれる以下パッケージを利用
$ conda list --show-channel-urls
mysql-connector-c         6.1.11               hccea1a4_0
mysql-connector-python    8.0.18           py37h3febbb0_1
openssl                   1.1.1d               h1de35cc_3
python                    3.7.4                h359304d_1

■MySQLサーバ

  • MySQL 5.7(デフォルト設定)

対策

DBコネクションを作成するときの引数に use_pure=True を指定し、利用するモジュールをデフォルトのC拡張版ではなくPython純正版に変更したところ接続できるようになりました。

7.1 Connector/Python Connection Arguments

test.py
import mysql.connector

conn = mysql.connector.connect(
    host='127.0.0.1',
    port='3306',
    user='user',
    password='password',
    database='sample_db',
    use_pure=True  # ←追加
)
cursor = conn.cursor()

ざっと調べた限り、本エラーは mysql-connector-pythonとopensslの互換性の問題?に起因して発生しているようです。
私の環境では試してはいないですが、以下issueによるとopensslのバージョンを1.0.2にダウングレードすると接続できるようになったとのコメントがあります。

MySQLdb and mysql.connector are incompatible with openssl 1.1.1a #10646

なお、Python純正と比較してC実装版を使うほうがパフォーマンスが向上するらしいので、大量データを扱う場合は注意が必要そうです・・・。

Chapter 8 The Connector/Python C Extension
SSL Error when connecting on Linux/Mac using Openssl 1.1.1 #22n

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?