MySQL Connector/Python 開發人員指南  /  Connector/Python 程式碼範例  /  使用 Connector/Python 查詢資料

5.4 使用 Connector/Python 查詢資料

以下範例示範如何使用透過連線的 cursor() 方法建立的游標來查詢資料。傳回的資料會格式化並列印在主控台上。

任務是選取所有在 1999 年僱用的員工,並將其姓名和雇用日期列印到主控台。

import datetime
import mysql.connector

cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()

query = ("SELECT first_name, last_name, hire_date FROM employees "
         "WHERE hire_date BETWEEN %s AND %s")

hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)

cursor.execute(query, (hire_start, hire_end))

for (first_name, last_name, hire_date) in cursor:
  print("{}, {} was hired on {:%d %b %Y}".format(
    last_name, first_name, hire_date))

cursor.close()
cnx.close()

首先,我們開啟與 MySQL 伺服器的連線,並將連線物件儲存在變數 cnx 中。然後,我們使用連線的 cursor() 方法建立一個新的游標,預設為 MySQLCursor 物件。

在先前的範例中,我們將 SELECT 陳述式儲存在變數 query 中。請注意,我們在使用未加引號的 %s 標記,以代表日期。Connector/Python 會將 hire_starthire_end 從 Python 類型轉換為 MySQL 可理解的資料類型,並新增必要的引號。在此案例中,它會將第一個 %s 取代為 '1999-01-01',第二個取代為 '1999-12-31'

然後,我們使用 execute() 方法執行儲存在 query 變數中的操作。用於取代查詢中 %s 標記的資料會以 Tuple 形式傳遞:(hire_start, hire_end)

執行查詢後,MySQL 伺服器已準備好傳送資料。結果集可能為零列、一列或 1 億列。根據預期的資料量,您可以使用不同的技術來處理此結果集。在此範例中,我們將 cursor 物件用作迭代器。列中的第一欄儲存在變數 first_name 中,第二欄儲存在 last_name 中,第三欄儲存在 hire_date 中。

我們使用 Python 內建的 format() 函式來格式化輸出並列印結果。請注意,hire_date 已由 Connector/Python 自動轉換為 Python datetime.date 物件。這表示我們可以輕鬆地以更易於閱讀的形式格式化日期。

輸出應該會像這樣

..
Wilharm, LiMin was hired on 16 Dec 1999
Wielonsky, Lalit was hired on 16 Dec 1999
Kamble, Dannz was hired on 18 Dec 1999
DuBourdieux, Zhongwei was hired on 19 Dec 1999
Fujisawa, Rosita was hired on 20 Dec 1999
..