Share via


快速入門:使用 Python 連線和查詢 適用於 MySQL 的 Azure 資料庫 中的數據 - 彈性伺服器

適用於:適用於 MySQL 的 Azure 資料庫 - 彈性伺服器

在本快速入門中,您會使用 Python 連線到 適用於 MySQL 的 Azure 資料庫 彈性伺服器。 然後,您可以使用 SQL 語句,從 Mac、Ubuntu Linux 和 Windows 平台查詢、插入、更新和刪除資料庫中的數據。

本文假設您已熟悉使用 Python 進行開發,但不熟悉 適用於 MySQL 的 Azure 資料庫 彈性伺服器。

必要條件

  • 具有有效訂用帳戶的 Azure 帳戶。

    如果您沒有 Azure 訂用帳戶,請在開始之前建立 Azure 免費帳戶 。 目前,使用 Azure 免費帳戶,您可以試用 適用於 MySQL 的 Azure 資料庫 - 彈性伺服器免費 12 個月。 如需詳細資訊,請參閱免費試用 適用於 MySQL 的 Azure 資料庫 - 彈性伺服器。

  • 適用於 MySQL 的 Azure 資料庫 彈性伺服器實例。 若要建立 適用於 MySQL 的 Azure 資料庫 彈性伺服器實例,請參閱使用 Azure 入口網站 建立 適用於 MySQL 的 Azure 資料庫 彈性伺服器實例或使用 Azure CLI 建立 適用於 MySQL 的 Azure 資料庫 彈性伺服器實例。

準備用戶端工作站

  • 如果您使用私人存取建立彈性伺服器 (VNet 整合),則必須從與伺服器位於相同 VNet 內的資源連線到您的伺服器。 您可以建立虛擬機,並將其新增至使用彈性伺服器建立的 VNet。 請參閱使用 Azure CLI 建立和管理 適用於 MySQL 的 Azure 資料庫 彈性伺服器虛擬網路。
  • 如果您使用公用存取(允許的IP位址)建立彈性伺服器,您可以將本機IP位址新增至您伺服器上的防火牆規則清單。 請參閱使用 Azure CLI 建立和管理 適用於 MySQL 的 Azure 資料庫 彈性伺服器防火牆規則。

安裝 Python 和 MySQL 連接器

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

注意

本快速入門會使用原始 SQL 查詢方法來連線到 MySQL。 如果您使用 Web 架構,請使用適用於架構的建議連接器,例如 Django 的 mysqlclient

  1. 下載並安裝 適用於您 OS 的 Python 3.7 或更新版本 。 請務必將 Python 新增至您的 PATH,因為 MySQL 連接器需要。

  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
    

    您也可以從 mysql.com 安裝適用於 MySQL 的 Python 連接器。 如需適用於 Python 之 MySQL 連線 or 的詳細資訊,請參閱 MySQL 連線 or/Python 開發人員指南

取得連線資訊

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

  1. 登入 Azure 入口網站

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

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

程式碼範例

執行下列所述的 Python 程式代碼範例

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

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

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

  3. 將檔案儲存在擴展名為.py的項目資料夾中,例如 C:\pythonmysql\createtable.py/home/username/pythonmysql/createtable.py

  4. 若要執行程式碼,請開啟命令提示字元或 bash 殼層,並將目錄變更為項目資料夾,例如 cd pythonmysqlpython輸入命令,後面接著檔名,例如 python createtable.py,然後按 Enter。

    注意

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

建立數據表並插入數據

使用下列程式代碼連線到伺服器和資料庫、建立數據表,以及使用 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.")

下一步