クイック スタート:Python を使用して Azure Database for MySQL に接続してデータを照会する

適用対象: Azure Database for MySQL - 単一サーバー

重要

Azure Database for MySQL シングル サーバーは廃止パスにあります。 Azure Database for MySQL フレキシブル サーバーにアップグレードすることを強くお勧めします。 Azure Database for MySQL フレキシブル サーバーへの移行の詳細については、Azure Database for MySQL シングル サーバーの現状に関するページを参照してください

このクイックスタートでは、Python を使用して Azure Database for MySQL に接続します。 Mac、Ubuntu Linux、Windows の各プラットフォームから SQL ステートメントを使用して、データベース内のデータを照会、挿入、更新、削除できます。

前提条件

このクイックスタートでは、以下が必要です。

  • アクティブなサブスクリプションが含まれる Azure アカウント。 無料でアカウントを作成できます

  • Azure portal を使用して、Azure Database for MySQL シングル サーバーを作成します
    Azure CLI を使用して、Azure Database for PostgreSQL の単一サーバーを作成します (まだない場合)。

  • パブリック アクセスとプライベート アクセスのどちらを使用しているかに基づいて、次のいずれかのアクションを実行して、接続を有効にします。

    アクション 接続方法 ハウツー ガイド
    ファイアウォール規則を構成する パブリック ポータル
    CLI
    サービス エンドポイントを構成する パブリック ポータル
    CLI
    プライベート リンクを構成する プライベート ポータル
    CLI
  • データベースと管理者以外のユーザーを作成する

Python と MySQL コネクタのインストール

次の手順を使用して、お使いのコンピューターに Python と Python 用 MySQL コネクタをインストールします。

注意

このクイックスタートでは、MySQL Connector/Python 開発者ガイドを使用しています。

  1. ご使用の OS に Python 3.7 以上をダウンロードしてインストールします。 MySQL コネクタで必要となるため、必ず Python を PATH に追加します。

  2. コマンド プロンプトまたは bash シェルを開き、大文字の V スイッチを指定して python -V を実行して、Python のバージョンを確認します。

  3. pip パッケージ インストーラーは、Python の最新バージョンに含まれています。 pip install -U pip を実行して、pip を最新バージョンに更新します。

    pip がインストールされていない場合は、get-pip.py を使用してダウンロードおよびインストールできます。 詳細については、「インストール」を参照してください。

  4. pip を使用して、Python 用 MySQL コネクタとその依存関係をインストールします。

    pip install mysql-connector-python
    

接続情報の取得

Azure portal から Azure Database for MySQL に接続するために必要な接続情報を取得します。 サーバー名、データベース名、およびログイン資格情報が必要です。

  1. Azure portal にサインインします。

  2. ポータルの検索バーで、作成した Azure Database for MySQL サーバー (たとえば、mydemoserver) を検索して選択します。

    Azure Database for MySQL サーバー名

  3. サーバーの [概要] ページから、 [サーバー名][サーバー管理者ログイン名] を書き留めます。 パスワードを忘れた場合も、このページからパスワードをリセットすることができます。

    Azure Database for MySQL サーバー名 2

Python コード サンプルの実行

この記事の各コード例では、次のことを行います。

  1. テキスト エディターで新しいファイルを作成します。

  2. ファイルにコード例を追加します。 コード内の <mydemoserver><myadmin><mypassword>、および <mydatabase> の各プレースホルダーを、実際の MySQL サーバーとデータベースの値に置き換えます。

  3. Azure Database for MySQL のサーバー上では SSL は既定で有効になっています。 ローカル環境から接続するには、DigiCertGlobalRootG2 SSL 証明書をダウンロードする必要がある場合があります。 コードの ssl_ca 値を、コンピューター上のこのファイルへのパスに置き換えます。

  4. .py 拡張子を付けてファイルをプロジェクト フォルダーに保存します (たとえば、C:\pythonmysql\createtable.py/home/username/pythonmysql/createtable.py)。

  5. コードを実行するために、コマンド プロンプトまたは bash シェルを開き、ディレクトリを対象のプロジェクト フォルダー (たとえば、cd pythonmysql) に変更します。 python コマンドに続けてファイル名 (たとえば、python createtable.py) を入力し、Enter キーを押します。

    注意

    Windows で python.exe が見つからない場合は、Python のパスを PATH 環境変数に追加するか、python.exe への完全パス (たとえば、C:\python27\python.exe createtable.py) を指定してください。

手順 1:テーブルを作成してデータを挿入する

次のコードを使用して、サーバーとデータベースに接続し、テーブルを作成した後、INSERT SQL ステートメントを使用してデータを読み込みます。コードによって mysql.connector ライブラリがインポートされ、以下のメソッドが使用されます。

  • connect() 関数は、config コレクションの引数を使用して、Azure Database for MySQL に接続します。
  • cursor. execute() メソッドは、MySQL データベースに対して SQL クエリを実行します。
  • cursor.close() は、カーソルの使用が終了したときに使用されます。
  • conn.close() は、接続を閉じます。
import mysql.connector
from mysql.connector import errorcode

# Obtain connection string information from the portal

config = {
  'host':'<mydemoserver>.mysql.database.azure.com',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
}

# 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.")

手順 2:データの読み取り

接続し、SELECT SQL ステートメントを使用してデータを読み取るには、次のコードを使用します。 コードは mysql.connector ライブラリをインポートし、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>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
}

# 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.")

手順 3:データの更新

接続し、UPDATE SQL ステートメントを使用してデータを更新するには、次のコードを使用します。 コードは mysql.connector ライブラリをインポートし、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>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
}

# 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;", (300, "apple"))
  print("Updated",cursor.rowcount,"row(s) of data.")

  # Cleanup
  conn.commit()
  cursor.close()
  conn.close()
  print("Done.")

手順 4:データの削除

接続し、DELETE SQL ステートメントを使用してデータを削除するには、次のコードを使用します。 コードは mysql.connector ライブラリをインポートし、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>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
}

# 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.")  

リソースをクリーンアップする

このクイックスタートで使用したすべてのリソースをクリーンアップするには、次のコマンドを使用してリソース グループを削除します。

az group delete \
    --name $AZ_RESOURCE_GROUP \
    --yes

次のステップ