調(diào)用cursor.callproc
后獲取存儲(chǔ)過程的結(jié)果取決于以下因素:
DBAPI 規(guī)范 在 上有這樣的說法光標(biāo).callproc
:
實(shí)際上,只有當(dāng)過程返回單行且列數(shù)與 INOUT 和 OUT 參數(shù)的數(shù)量匹配時(shí),使用 Cursor.callproc 的返回值才有效,因此存在一些問題結(jié)果處理方式的變化。
以下是主要 MySQL Python 連接器包處理這些情況的方式 - MySQL 連接器,mysqlclient (MySQLdb) 和 PyMySQL。
單行結(jié)果,通過 INOUT 或 OUT 參數(shù)返回
MySQL Connector 返回輸入序列的修改副本作為 cursor.callproc
的返回值;該值是一個(gè)元組。
params = [in_param, out_param1, out_param2] in_, out1, out2 = cursor.callproc("test_proc", params)
mysqlclient和PyMySQL要求查詢數(shù)據(jù)庫(kù)獲取輸出參數(shù),然后通過游標(biāo)獲取結(jié)果;該值是元組的元組。要查詢的參數(shù)名稱的形式為'@_{procedure_name}_{params.index(param)}'
cursor.callproc("test_proc", params) cursor.execute("""SELECT @_test_proc_0, @_test_proc_1""") result = cursor.fetchall()
單個(gè)結(jié)果集中的一行或多行,未定義 INOUT 或 OUT 參數(shù)
MySQL Connector 通過光標(biāo)的 stored_results 方法(cursor.stored_results
不是 DBAPI 規(guī)范的一部分)
cursor.callproc("test_proc", params) results = [r.fetchall() for r in cursor.stored_results()]
mysqlclient 和 PyMySQL 通過游標(biāo)的 fetch* 方法公開結(jié)果
cursor.callproc("test_proc", params) results = cursor.fetchall()
多個(gè)結(jié)果集,未定義 INOUT 或 OUT 參數(shù)
MySQL Connector 通過游標(biāo)的 stored_results
方法公開結(jié)果
cursor.callproc("test_proc", params) results = [r.fetchall() for r in cursor.stored_results()]
mysqlclient 和 PyMySQL 要求在調(diào)用 cursor.nextset 前進(jìn)到下一個(gè)結(jié)果集。請(qǐng)注意,可能會(huì)返回一個(gè)額外的空結(jié)果集,這是調(diào)用過程的結(jié)果(如果通過 cursor.nextset
檢索結(jié)果集而不是僅調(diào)用 cursor.fetchall一次)。
cursor.callproc("test_proc", params) results = [cursor.fetchall()] while cursor.nextset(): results.append(cursor.fetchall())
版本信息
$ mysql --version mysql Ver 15.1 Distrib 10.1.41-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2 $ pip list | grep -i mysql mysql-connector-python 8.0.18 mysqlclient 1.4.6 PyMySQL 0.9.3
您是否嘗試過選擇其中一個(gè)結(jié)果集?
for result in cursor.stored_results(): people = result.fetchall()
即使您只有一個(gè) SELECT
stmt,它也可能會(huì)分配多個(gè)結(jié)果集。我知道在 PHP 的 MySQLi 存儲(chǔ)過程中這樣做是為了允許 INOUT 和 OUT 變量返回(同樣,你沒有,但也許它無(wú)論如何都在分配)。
我正在使用的完整代碼(正在運(yùn)行)是:
import mysql.connector cnx = mysql.connector.connect(user='me',password='pw',host='localhost',database='mydb') cnx._open_connection() cursor = cnx.cursor() cursor.callproc("getperson",[1]) for result in cursor.stored_results(): people=result.fetchall() for person in people: print person cnx.close()