首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

MySQL Connector/Python 呼叫預存程序並取得結果集完整範例

     編輯:MySQL 綜合教學

MySQL Connector/Python 呼叫預存程序並取得結果集

使用 MySQL Connector/Python 呼叫會回傳結果集(如 SELECT)的預存程序時,需透過游標的 stored_results() 方法迭代取得每個結果集的游標,再逐列讀取資料。

完整程式碼範例

import mysql.connector

# 建立連線
cnx = mysql.connector.connect(
    user='scott',
    password='tiger',
    database='mining'
)
cur = cnx.cursor()

# 建立示範用預存程序(查詢 Slave 狀態)
cur.execute("DROP PROCEDURE IF EXISTS slave_status")
proc_sql = """
CREATE PROCEDURE slave_status ()
BEGIN
    SHOW SLAVE STATUS;
END
"""
cur.execute(proc_sql)

# 呼叫預存程序
cur.callproc('slave_status')

# 關鍵:透過 stored_results() 取得所有結果集的游標迭代器
for result_cursor in cur.stored_results():
    for row in result_cursor:
        print(row[0])  # 印出第一欄(如 Slave_IO_State)

# 關閉資源
cur.close()
cnx.close()

輸出範例

shell$ python foo.py
Waiting for master to send event

關鍵點解析

  1. stored_results():回傳一個迭代器,依序產生每個結果集的 MySQLCursorBuffered 物件。
  2. with_rows 屬性:可用於判斷游標是否包含資料列(如 SELECT 會有,INSERT 則無),避免對無結果集的游標迭代。
  3. 多結果集處理:若預存程序包含多個 SELECT,迴圈會依序處理每一個。

替代寫法:檢查 with_rows

for result_cursor in cur.stored_results():
    if result_cursor.with_rows:
        rows = result_cursor.fetchall()
        for row in rows:
            print(row)
    else:
        print("此結果集無資料列(如 DDL/DML)")

此模式適用於所有回傳結果集的預存程序呼叫,是 Connector/Python 官方建議的標準作法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved