このクイックスタートでは、Python を使用して Azure Database for MySQL フレキシブル サーバーに接続します。 Mac、Ubuntu Linux、Windows の各プラットフォームから SQL ステートメントを使用して、データベース内のデータを照会、挿入、更新、削除できます。
この記事では、Python を使用した開発には慣れているものの、Azure Database for MySQL フレキシブル サーバーの使用は初めてであるユーザーを想定しています。
前提条件
- アクティブなサブスクリプションが含まれる Azure アカウント。
Azure サブスクリプションをお持ちでない場合は、開始する前に Azure 無料アカウントを作成してください。 現在、Azure 無料アカウントがあれば、Azure Database for MySQL - フレキシブル サーバーを 12 か月間無料でお試しいただけます。 詳細については、「Azure 無料アカウントを使用して Azure Database for MySQL - フレキシブル サーバーを無料で試す」を参照してください。
- Azure Database for MySQL の柔軟なサーバーインスタンス。 Azure Database for MySQL フレキシブル サーバー インスタンスを作成するには、「クイックスタート: Azure portal を使用して Azure Database for MySQL のインスタンスを作成する」または「クイックスタート: Azure CLI を使用して Azure Database for MySQL - フレキシブル サーバーのインスタンスを作成する」を参照してください。
クライアント ワークステーションを準備する
- プライベート アクセス (仮想ネットワーク統合) を使用してフレキシブル サーバーを作成した場合は、サーバーと同じ仮想ネットワーク内のリソースからサーバーに接続する必要があります。 仮想マシンを作成し、フレキシブル サーバーで作成された仮想ネットワークに追加できます。 「Azure CLI を使用した Azure Database for MySQL - フレキシブル サーバーの仮想ネットワークの作成と管理」を参照してください。
- "パブリック アクセス (使用できる IP アドレス) " を指定してフレキシブル サーバーを作成した場合は、サーバー上のファイアウォール規則のリストにローカル IP アドレスを追加できます。 「Azure CLI を使用して、Azure Database for MySQL - フレキシブル サーバーのファイアウォール規則を管理する」を参照します。
Python と MySQL コネクタのインストール
次の手順を使用して、お使いのコンピューターに Python と Python 用 MySQL コネクタをインストールします。
注意
このクイックスタートでは、未加工の SQL クエリの手法を使用して、MySQL に接続します。 Web フレームワークを使用している場合は、それらのフレームワークに対して推奨されているコネクタを使用してください (たとえば、Django の場合は mysqlclient)。
ご使用の OS に Python 3.7 以上をダウンロードしてインストールします。 MySQL コネクタで必要となるため、必ず Python を
PATHに追加します。コマンド プロンプトまたは
bashシェルを開き、大文字の V スイッチを指定してpython -Vを実行して、Python のバージョンを確認します。pipパッケージ インストーラーは、Python の最新バージョンに含まれています。pipを実行して、pip install -U pipを最新バージョンに更新します。pipがインストールされていない場合は、get-pip.pyを使用してダウンロードおよびインストールできます。 詳細については、「インストール」を参照してください。pipを使用して、Python 用 MySQL コネクタとその依存関係をインストールします。pip install mysql-connector-pythonMySQL 用 Python コネクタは、mysql.com からインストールすることもできます。 Python 用 MySQL コネクタの詳細については、「MySQL Connector/Python 開発者ガイド」を参照してください。
接続情報の取得
Azure portal から Azure Database for MySQL フレキシブル サーバーに接続するために必要な接続情報を取得します。 サーバー名、データベース名、およびサインイン資格情報が必要です。
Azure portal にサインインします。
ポータルの検索バーで、作成した Azure Database for MySQL フレキシブル サーバー インスタンス (mydemoserver など) を検索して選択します。
サーバーの [概要] ページから、 [サーバー名] と [サーバー管理者ログイン名] を書き留めます。 パスワードを忘れた場合も、このページからパスワードをリセットすることができます。
コード サンプル
以下に示す Python コード サンプルを実行する
この記事の各コード例では、次のことを行います。
テキスト エディターで新しいファイルを作成します。
ファイルにコード例を追加します。 コード内の
<mydemoserver>、<myadmin>、<mypassword>、および<mydatabase>の各プレースホルダーを、実際の MySQL サーバーとデータベースの値に置き換えます。.py 拡張子を付けてファイルをプロジェクト フォルダーに保存します (たとえば、C:\pythonmysql\createtable.py、 /home/username/pythonmysql/createtable.py)。
コードを実行するために、コマンド プロンプトまたは
bashシェルを開き、ディレクトリを対象のプロジェクト フォルダー (たとえば、cd pythonmysql) に変更します。pythonコマンドに続けてファイル名 (たとえば、python createtable.py) を入力し、Enter キーを押します。注意
Windows では、python.exe が見つからない場合は、PYTHON パスを PATH 環境変数に追加するか、への完全なパスを指定する必要があります。
テーブルを作成してデータを挿入する
次のコードを使用して、サーバーとデータベースに接続し、テーブルを作成した後、INSERT SQL ステートメントを使用してデータを読み込みます。
このコードでは、mysql.connector ライブラリをインポートし、connect() 関数を使用して、config コレクション内の引数を使用してフレキシブル サーバーに接続します。 このコードでは、接続でカーソルを使用し、cursor.execute() メソッドによって MySQL データベースに対する SQL クエリを実行します。
import mysql.connector
from mysql.connector import errorcode
# Obtain connection string information from the portal
config = {
'host':'<mydemoserver>.mysql.database.azure.com',
'user':'<myadmin>',
'password':'<mypassword>',
'database':'<mydatabase>'
}
# Construct connection string
try:
conn = mysql.connector.connect(**config)
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cursor = conn.cursor()
# Drop previous table of same name if one exists
cursor.execute("DROP TABLE IF EXISTS inventory;")
print("Finished dropping table (if existed).")
# Create table
cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
print("Finished creating table.")
# Insert some data into table
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
print("Inserted",cursor.rowcount,"row(s) of data.")
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
print("Inserted",cursor.rowcount,"row(s) of data.")
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
print("Inserted",cursor.rowcount,"row(s) of data.")
# Cleanup
conn.commit()
cursor.close()
conn.close()
print("Done.")
データの読み取り
接続し、SELECT SQL ステートメントを使用してデータを読み取るには、次のコードを使用します。
このコードでは、mysql.connector ライブラリをインポートし、connect() 関数を使用して、config コレクション内の引数を使用してフレキシブル サーバーに接続します。 このコードでは、接続でカーソルを使用し、cursor.execute() メソッドによって MySQL データベースに対する SQL クエリを実行します。
このコードでは、fetchall() メソッドを使用してデータ行を読み取り、結果セットをコレクション行に保持し、for 反復子を使用して行をループ処理します。
import mysql.connector
from mysql.connector import errorcode
# Obtain connection string information from the portal
config = {
'host':'<mydemoserver>.mysql.database.azure.com',
'user':'<myadmin>',
'password':'<mypassword>',
'database':'<mydatabase>'
}
# Construct connection string
try:
conn = mysql.connector.connect(**config)
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cursor = conn.cursor()
# Read data
cursor.execute("SELECT * FROM inventory;")
rows = cursor.fetchall()
print("Read",cursor.rowcount,"row(s) of data.")
# Print all rows
for row in rows:
print("Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2])))
# Cleanup
conn.commit()
cursor.close()
conn.close()
print("Done.")
データの更新
接続し、UPDATE SQL ステートメントを使用してデータを更新するには、次のコードを使用します。
このコードでは、mysql.connector ライブラリをインポートし、connect() 関数を使用して、config コレクション内の引数を使用してフレキシブル サーバーに接続します。 このコードでは、接続でカーソルを使用し、cursor.execute() メソッドによって MySQL データベースに対する SQL クエリを実行します。
import mysql.connector
from mysql.connector import errorcode
# Obtain connection string information from the portal
config = {
'host':'<mydemoserver>.mysql.database.azure.com',
'user':'<myadmin>',
'password':'<mypassword>',
'database':'<mydatabase>'
}
# Construct connection string
try:
conn = mysql.connector.connect(**config)
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cursor = conn.cursor()
# Update a data row in the table
cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (200, "banana"))
print("Updated",cursor.rowcount,"row(s) of data.")
# Cleanup
conn.commit()
cursor.close()
conn.close()
print("Done.")
データの削除
接続し、DELETE SQL ステートメントを使用してデータを削除するには、次のコードを使用します。
このコードでは、mysql.connector ライブラリをインポートし、connect() 関数を使用して、config コレクション内の引数を使用してフレキシブル サーバーに接続します。 このコードでは、接続でカーソルを使用し、cursor.execute() メソッドによって MySQL データベースに対する SQL クエリを実行します。
import mysql.connector
from mysql.connector import errorcode
# Obtain connection string information from the portal
config = {
'host':'<mydemoserver>.mysql.database.azure.com',
'user':'<myadmin>',
'password':'<mypassword>',
'database':'<mydatabase>'
}
# Construct connection string
try:
conn = mysql.connector.connect(**config)
print("Connection established.")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password.")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist.")
else:
print(err)
else:
cursor = conn.cursor()
# Delete a data row in the table
cursor.execute("DELETE FROM inventory WHERE name=%(param1)s;", {'param1':"orange"})
print("Deleted",cursor.rowcount,"row(s) of data.")
# Cleanup
conn.commit()
cursor.close()
conn.close()
print("Done.")