2015-05-25 64 views
0

我是python的新手,我在調用可能會生成信號的存儲過程時遇到問題(https://dev.mysql.com/doc/refman/5.5/en/signal.html)。我無法捕捉到信號作爲標準的mysql異常(與.net環境(C#)相反,它返回異常 - 如預期的那樣)。python 3.4和mysql信號

問題是,以下存儲過程在調用「SHOW WARNINGS」之後返回了mysql控制檯中的錯誤,但沒有用python處理,除了語法。

DROP PROCEDURE IF EXISTS `TEST_CALL_ME_ERROR`; 
DELIMITER // 
CREATE [email protected] PROCEDURE TEST_CALL_ME_ERROR() DETERMINISTIC 

    MAIN_BLOCK: BEGIN 

     SELECT 'THIS IS ONLY TEST' FROM DUAL; 
     SIGNAL SQLSTATE '01000' SET MESSAGE_TEXT = 'I AM THE ERROR.', MYSQL_ERRNO = 1001; 

END MAIN_BLOCK; 

我試圖從連接器(與MySQL C庫)pymysql和MySQL。因爲它是語法正確

try: 
    connection = mysql.connect(host=localhost, 
           user=root, 
           passwd= ** ** **, 
    db = "test", charset = 'utf8', port = 3306, raise_on_warnings = True) 
    cursor = connection.cursor() 
    cursor.callproc('TEST_CALL_ME_ERROR') 
except Exception as e: 
    print(e) # I expect to be here 

回答

0

存儲過程本身可能不會導致錯誤(雖然它的代碼輸出一個錯誤消息)。可能的話,打印結果會。您可以通過特意在存儲過程中寫入無效的語法來測試該理論。

考慮以下任何迭代在Try塊:

results = cursor.callproc('TEST_CALL_ME_ERROR',()) 
print(results) 

OR

cursor.callproc('TEST_CALL_ME_ERROR',()) 
results = cursor.fetchone() 
print(results) 

OR

cursor.execute('call TEST_CALL_ME_ERROR();') 
results = cursor.fetchone() 
print(results)