mysql-connector-python は、MySQL が提供する Python コネクタです。C 言語の標準関数ライブラリに依存しないため、より便利に使用できます。このトピックでは、Python を使用してアプリケーションを開発する際に、mysql-connector-python を使用して LindormTable に接続する方法について説明します。
前提条件
Python 3.8 以降のバージョンがインストールされていること。
インスタンスで MySQL 互換機能が有効になっていること。詳細については、「MySQL 互換機能を有効にする」をご参照ください。
ご利用のクライアントの IP アドレスが Lindorm インスタンスのホワイトリストに追加されていること。詳細については、「ホワイトリストの設定」をご参照ください。
操作手順
バージョン 8.0.11 の mysql-connector-python をインストールします。
pip install mysql-connector-python==8.0.11コマンドを実行してインストールすることもできます。接続を確立し、パラメーターを設定します。
connection = mysql.connector.connect(host='<LindormTable endpoint for MySQL.>', port=33060, user='<Username>', passwd='<Password>', database='<Database name>') cursor = connection.cursor(prepared=True)パラメーター
パラメーター
説明
host
Lindorm ワイドテーブルの SQL アドレスです。末尾のコロンとポート番号
:33060は削除してください。エンドポイントの取得方法の詳細については、「接続エンドポイントの表示」をご参照ください。重要アプリケーションが Elastic Compute Service (ECS) インスタンスにデプロイされており、その ECS インスタンスが Lindorm インスタンスと同じ VPC 内にある場合は、VPC 経由で Lindorm インスタンスに接続することを推奨します。それ以外の場合は、インターネット経由で Lindorm インスタンスに接続してください。インターネット経由で Lindorm インスタンスに接続するには、インスタンスのパブリックエンドポイントを有効にする必要があります。詳細については、「LindormSearch の有効化」をご参照ください。
port
LindormTable の MySQL プロトコルのポートです。値は
33060に固定されています。user
ユーザーのパスワードを忘れた場合は、LindormTable クラスター管理システムで変更できます。詳細については、「ユーザーパスワードの変更」をご参照ください。
passwd
database
接続先のデータベース名です。デフォルトでは、クライアントは default という名前のデータベースに接続されます。
LindormTable SQL を使用して LindormTable で操作を実行します。次のコードブロックは、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 を使用して Python から LindormTable に接続するには、次の 2 つのモードがあります。
直接接続モード:単一の操作や頻度の低いアクセスに適しています。操作ごとに接続が作成され、閉じられます。
接続プールモード:高頻度のアクセスに適しています。接続を再利用することで、パフォーマンスを向上させ、リソースのオーバーヘッドを削減します。
直接接続モード
次のコードは例です。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
import mysql.connector
# データベース接続を開きます。
# host: MySQL プロトコルを使用して LindormTable に接続するためのエンドポイント。
# port: MySQL プロトコルを使用して LindormTable に接続するためのポート。デフォルト値は 33060 です。
# user: LindormTable に接続するためのユーザー名。
# passwd: ユーザー名に対応するパスワード。
# 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()書き込む文字列に JSON 文字列内の二重引用符 (") などの特殊文字が含まれている場合は、上記の例に示すように、prepared=True パラメーター設定を使用します。これにより、Lindorm に書き込まれるデータにエスケープ文字が追加されるのを防ぎます。
接続プールモード
次のコードは例です。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
import mysql.connector
from mysql.connector import pooling
# 接続プールを作成します。
# pool_name: 接続プールの名前。
# pool_size: 接続プールのサイズ。これはプール内の最大接続数です。必要に応じてこの値を変更してください。
# host: MySQL プロトコルを使用して LindormTable に接続するためのエンドポイント。
# port: MySQL プロトコルを使用して LindormTable に接続するためのポート。デフォルト値は 33060 です。
# user: LindormTable に接続するためのユーザー名。
# passwd: ユーザー名に対応するパスワード。
# 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()