mysql-connector-python は MySQL が提供する Python 用コネクタです。C 言語の標準関数ライブラリに依存せず、使いやすい特徴があります。本トピックでは、Python を使用してアプリケーションを開発する際に、mysql-connector-python を使って LindormTable に接続する方法について説明します。
前提条件
Python 3.8 以降のバージョンがインストールされていること。
インスタンスで MySQL 互換性機能が有効になっていること。詳細については、「MySQL 互換性機能の有効化」をご参照ください。
ご利用のクライアントの IP アドレスが Lindorm インスタンスのホワイトリストに追加されていること。詳細については、「ホワイトリストの設定」をご参照ください。
操作手順
mysql-connector-python バージョン 8.0.15 を、
pip install mysql-connector-python==8.0.15コマンドを実行してインストールします。接続を確立し、パラメーターを設定します。
connection = mysql.connector.connect(host='<LindormTable endpoint for MySQL.>', port=33060, user='<Username>', passwd='<Password>', database='<Database name>') cursor = connection.cursor(prepared=True)パラメーター
パラメーター
説明
host
コロンとポート番号 (
:33060) を除いた Lindorm ワイドテーブルの SQL アドレス。エンドポイントの取得方法の詳細については、「エンドポイントの確認」をご参照ください。重要ご利用のアプリケーションが Elastic Compute Service (ECS) インスタンス上にデプロイされており、その ECS インスタンスが Lindorm インスタンスと同一の VPC 内にある場合は、VPC 経由での Lindorm インスタンスへの接続を推奨します。それ以外の場合は、インターネット経由で Lindorm インスタンスに接続してください。インターネット経由で Lindorm インスタンスに接続するには、インスタンスのパブリックエンドポイントを有効にする必要があります。詳細については、「LindormSearch の有効化」をご参照ください。
port
LindormTable に MySQL で接続する際に使用するポートです。値は固定で
33060です。user
パスワードを忘れた場合は、LindormTable クラスター管理システムから再設定できます。詳細については、「パスワードの変更」をご参照ください。
passwd
database
接続先のデータベース名です。デフォルトでは、クライアントは default という名前のデータベースに接続されます。
LindormTable ではワイドテーブル SQL 構文を使用して、テーブル作成などの操作が可能です。
sql_create_table = ("create table if not exists test_python(c1 integer, c2 integer, c3 varchar, primary key(c1))") print(sql_create_table) cursor.execute(sql_create_table)
コード例
mysql-connector-python ドライバーは、LindormTable への接続において以下の 2 つのモードをサポートしています。
ダイレクト接続モード:一時的な操作やアクセス頻度が低い場合に適しています。各操作ごとに新しい接続を開き、閉じます。
接続プールモード:頻繁なアクセスに適しています。接続を再利用することでパフォーマンスを向上させ、オーバーヘッドを削減します。
ダイレクト接続モード
以下のサンプルコードをご参照ください。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
import mysql.connector
# データベース接続を確立します。
# host には LindormTable の MySQL 用エンドポイントを設定します。
# port には LindormTable に MySQL で接続する際に使用するポート(デフォルトは 33060)を設定します。
# user には LindormTable に接続するユーザー名を設定します。
# passwd には LindormTable に接続するパスワードを設定します。
# database には LindormTable 内のデータベース名を設定します。
connection = mysql.connector.connect(host='ld-bp1hn6yq0yb34****-proxy-sql-lindorm-public.lindorm.rds.aliyuncs.com', port=33060,user='root', passwd='test',database='default')
# カーソルを作成し、prepared=True を指定します。
cursor = connection.cursor(prepared=True)
# テーブルを作成します。
sql_create_table = ("create table if not exists test_python(c1 integer, c2 integer, c3 varchar, primary key(c1))")
print(sql_create_table)
cursor.execute(sql_create_table)
# データを挿入します。
sql_upsert = "upsert into test_python(c1, c2, c3) values(?, ?, ?)"
print(sql_upsert)
# 単一行を挿入します。
cursor.execute(sql_upsert, (1, 1, '1'))
cursor.execute(sql_upsert, (2, 2, json.dumps({"key": "value2"})))
# 2 行をバッチで挿入します。
sql_upsert_batch = ("upsert into test_python(c1, c2, c3) values(?, ?, ?), (?, ?, ?)")
cursor.execute(sql_upsert_batch, (3, 3, '3' , 4, 4, json.dumps({"key": "value4"})))
# データを削除します。
sql_delete = "delete from test_python where c1 = ?"
print(sql_delete)
cursor.execute(sql_delete, (3,))
# データを更新します。
sql_update = "upsert into test_python(c1, c2, c3) values(?, ?, ?)"
print(sql_update)
cursor.execute(sql_update, (1, 2, '2'))
# 特定のデータをクエリします。
sql_select = "select * from test_python where c1 = ?"
print(sql_select)
cursor.execute(sql_select, (4,))
rows = cursor.fetchall()
print(rows)
# すべてのデータをクエリします。
sql_select_all = "select * from test_python"
print(sql_select_all)
cursor.execute(sql_select_all)
rows = cursor.fetchall()
print(rows)
# カーソルを閉じます。
cursor.close()
# 接続を閉じます。
connection.close()書き込む文字列に二重引用符 (") などの特殊文字が含まれる場合は、上記の例のように prepared=True を指定することで、LindormTable に書き込まれるデータが誤ってエスケープされるのを防げます。
接続プールモード
以下のサンプルコードをご参照ください。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
import mysql.connector
from mysql.connector import pooling
# 接続プールを作成します。
# pool_name には接続プールの名前を設定します。
# pool_size にはプール内の最大接続数を設定します。ワークロードに応じてこの値を調整してください。
# host には LindormTable の MySQL 用エンドポイントを設定します。
# port には LindormTable に MySQL で接続する際に使用するポート(デフォルトは 33060)を設定します。
# user には LindormTable に接続するユーザー名を設定します。
# password には LindormTable に接続するパスワードを設定します。
# database には LindormTable 内のデータベース名を設定します。
connection_pool = pooling.MySQLConnectionPool(
pool_name="mypool",
pool_size=20,
host='11.166.XX.X',
port=33060,
user='root',
password='root',
database='default',
)
# プールから接続を取得します。
connection = connection_pool.get_connection()
# カーソルを作成し、prepared=True を指定します。
cursor = connection.cursor(prepared=True)
# テーブルを削除します。
sql_drop_table = "drop table if exists test_python"
print(sql_drop_table)
cursor.execute(sql_drop_table)
# テーブルを作成します。
sql_create_table = ("create table test_python(c1 integer, c2 integer, c3 varchar, primary key(c1))")
print(sql_create_table)
cursor.execute(sql_create_table)
# 単一行を挿入します。
sql_upsert = "insert into test_python(c1, c2, c3) values(?, ?, ?)"
print(sql_upsert)
cursor.execute(sql_upsert, (1, 1, '1'))
cursor.execute(sql_upsert, (2, 2, '2'))
# 3 行をバッチで挿入します。
sql_upsert_batch = "insert into test_python(c1, c2, c3) values(?, ?, ?), (?, ?, ?), (?, ?, ?)"
cursor.execute(sql_upsert_batch, (3, 3, '3', 4, 4, '4', 5, 5, '5'))
# データを削除します。
sql_delete = "delete from test_python where c1 = ?"
print(sql_delete)
cursor.execute(sql_delete, (3,))
# データを更新します。
sql_update = "upsert into test_python(c1, c2, c3) values(?, ?, ?)"
print(sql_update)
cursor.execute(sql_update, (1, 2, '2'))
# 特定のデータをクエリします。
sql_select = "select * from test_python where c1 = ?"
print(sql_select)
cursor.execute(sql_select, (4,))
rows = cursor.fetchall()
print(rows)
# すべてのデータをクエリします。
sql_select_all = "select * from test_python"
print(sql_select_all)
cursor.execute(sql_select_all)
rows = cursor.fetchall()
print(rows)
# カーソルを閉じます。
cursor.close()
# 接続を閉じます。この際、接続は完全に閉じられるのではなく、プールに戻されます。
connection.close()