共用方式為


快速入門:使用 Python 連線和查詢適用於 MySQL 的 Azure 資料庫中的資料

適用於: 適用於 MySQL 的 Azure 資料庫 - 單一伺服器

重要

適用於 MySQL 的 Azure 資料庫單一伺服器位於淘汰路徑上。 強烈建議您升級至適用於 MySQL 的 Azure 資料庫彈性伺服器。 如需移轉至「適用於 MySQL 的 Azure 資料庫」彈性伺服器的詳細資訊,請參閱「適用於 MySQL 的 Azure 資料庫」單一伺服器會發生什麼事?

在本快速入門中,您將使用 Python 連線至適用於 MySQL 的 Azure 資料庫。 接著,您可以使用 SQL 陳述式來查詢、插入、更新和刪除 Mac、Ubuntu Linux 和 Windows 平台中的資料庫所含的資料。

必要條件

在本快速入門中,您需要:

安裝 Python 和 MySQL 連接器

使用下列步驟,在您的電腦上安裝 Python 和適用於 Python 的 MySQL 連接器:

注意

本快速入門使用 MySQL 連接器/Python 開發人員指南

  1. 為您的作業系統下載並安裝 Python 3.7 或更新版本。 請務必將 Python 新增至您的 PATH,因為 MySQL 連接器有此需要。

  2. 開啟命令提示字元或 bash 殼層,並以大寫 V 參數執行 python -V,以檢查您的 Python 版本。

  3. 最新版的 Python 中會包含 pip 套件安裝程式。 請執行 pip install -U pip,以將 pip 更新為最新版本。

    若未安裝 pip,您可以使用 get-pip.py 加以下載並安裝。 如需詳細資訊,請參閱安裝

  4. 使用 pip 安裝 Python 的 MySQL 連接器及其相依性:

    pip install mysql-connector-python
    

取得連線資訊

從 Azure 入口網站取得連線至適用於 MySQL 的 Azure 資料庫所需的連線資訊。 您需要伺服器名稱、資料庫名稱和登入認證。

  1. 登入 Azure 入口網站

  2. 在入口網站的搜尋列中,搜尋並選取您所建立的「適用於 MySQL 的 Azure 資料庫」伺服器,例如 mydemoserver

    適用於 MySQL 的 Azure 資料庫 伺服器名稱

  3. 在伺服器的 [概觀] 頁面上,記下 [伺服器名稱] 和 [伺服器管理員登入名稱]。 如果您忘記密碼,您也可以從此頁面重設密碼。

    適用於 MySQL 的 Azure 資料庫 伺服器名稱 2

執行 Python 程式碼範例

針對本文中的每個程式碼範例:

  1. 在文字編輯器中建立新的檔案。

  2. 將程式碼範例新增至檔案。 在程式碼中,將 <mydemoserver><myadmin><mypassword><mydatabase> 預留位置取代為您的 MySQL 伺服器和資料庫的值。

  3. 適用於 MySQL 的 Azure 資料庫伺服器上預設會啟用 SSL。 您可能需要下載 DigiCertGlobalRootG2 SSL 憑證,才能從本機環境連線。 將程式碼中的 ssl_ca 值取代為您電腦上這個檔案的路徑。

  4. 將副檔名為 .py 的檔案儲存到專案資料夾中,例如 C:\pythonmysql\createtable.py/home/username/pythonmysql/createtable.py

  5. 若要執行程式碼,請開啟命令提示字元或 cd pythonmysql 殼層,並將目錄切換至您的專案資料夾,例如 bash。 輸入後面接著檔案名稱的 python 命令 (例如 python createtable.py),然後按 Enter 鍵。

    注意

    在 Windows 上,如果找不到 python.exe,您可能需要將 Python 路徑新增至 PATH 環境變數中,或提供 python.exe 的完整路徑,例如 C:\python27\python.exe createtable.py

步驟 1:建立資料表及插入資料

使用下列程式碼搭配 INSERT SQL 陳述式連線至伺服器和資料庫、建立資料表,並載入資料。此程式碼會匯入 mysql.connector 程式庫,並使用下列方法:

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

下一步