2013-03-10 57 views
8

由於某些奇怪的原因,我無法從Python測試應用程序中的callproc調用中獲取結果。在MqSQL 47年2月5日的存儲過程是這樣的:無法使用Python光標返回存儲過程的結果

現在,使用PyCharm與Python 3.3,我似乎無法調用此存儲過程來檢索任何東西。此代碼得到我想要的結果:

import mysql.connector 

cnx = mysql.connector.connect(user='root', host='127.0.0.1', database='mytestdb') 
cnx._open_connection() 
cursor = cnx.cursor() 

cursor.execute("select * from person where person.person_id = 1") 
people = cursor.fetchall() 

for person in people: 
    print(person) 

cnx.close() 

但這個代碼或者cursor.fetchall()或cursor.fetchone()...

import mysql.connector 

cnx = mysql.connector.connect(user='root', host='127.0.0.1', database='mytestdb') 
cnx._open_connection() 
cursor = cnx.cursor() 

cursor.callproc("getperson", [1]) 
people = cursor.fetchall() 

for person in people: 
    print(person) 

cnx.close() 

...返回「mysql.connector。 errors.InterfaceError:沒有結果集要從中讀取。「這裏有一個額外的古怪行爲時使用像這樣的cursor.execute()方法...

import mysql.connector 

cnx = mysql.connector.connect(user='root', host='127.0.0.1', database='mytestdb') 
cnx._open_connection() 
cursor = cnx.cursor() 

cursor.execute("call getperson(1)") 
people = cursor.fetchall() 

for person in people: 
    print(person) 

cnx.close() 

...因爲它產生了「mysql.connector.errors.InterfaceError:使用cmd_query_iter與多個查詢語句」,其次是「mysql.connector.errors.InterfaceError:執行多個語句時使用multi = True」,儘管我只返回一個查詢結果而不是多個結果集。 MySQL Python連接器是否將存儲過程的執行調用視爲雙重查詢?我怎樣才能調用存儲過程並獲得我的結果?我真的不想在我的代碼中使用動態SQL。感謝您提供任何建議!

回答

11

您是否嘗試過採摘結果集的一個?

for result in cursor.stored_results(): 
    people = result.fetchall() 

這可能是因爲它是爲分配多個結果,即使你只有一個SELECT語句。我知道在PHP的MySQLi存儲過程中,這樣做是爲了允許INOUT和OUT變量返回(同樣,你沒有,但也許它是分配的)。

我使用(這是工作)的完整源代碼:

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() 
0

爲什麼不試試這種方式

cursor.callproc("getperson", ['1']) 
+0

那不是多個SQL服務器的語法比MySQL? – 2013-03-10 08:24:47

+0

因爲這不是MySQL PL/SQL中的有效命令。這是SQL Server的T-SQL的有效命令,但這不是我用於此項目的。調用存儲過程的MySQL語法是'call proc_name([arguments])'。 – gfish3000 2013-03-10 08:28:52