[英]Trapping MySQL Warnings In Python
我想在Python中捕獲並記錄MySQL警告。 例如,如果在沒有此類數據庫時提交'DROP DATABASE IF EXISTS database_of_armaments'
,MySQL會向標准錯誤發出警告。 我想抓住這個並記錄它,但即使在try / else語法中,仍然會出現警告消息。
try / except語法確實捕獲MySQL錯誤(例如,提交類似'DRP DATABASE database_of_armaments'
的拼寫錯誤)。
我已經嘗試了<<except.MySQLdb.Warning>>
- 沒有運氣。 我查看了警告模塊,但不明白如何將其合並到try / else語法中。
具體來說,我如何使以下(或類似的東西)工作。
GIVEN:數據庫'database_of_armaments'不存在。
try:
cursor.execute('DROP DATABASE IF EXISTS database_of_armaments')
except: <<WHAT DO I PUT HERE?>>
print 'There was a MySQL warning.'
<<AND what goes here if I want to get and manipulate information about the warning?>>
更新:
感謝您的評論。 我曾嘗試過這些並且它們不起作用 - 但我一直在使用我為連接編寫的DatabaseConnection類,以及要執行的runQuery()方法。 當我在類外部創建一個連接和光標時,try / except異常捕獲了“編程錯誤”,除了MySQLdb.ProgrammingError工作的廣告。
所以現在我必須弄清楚我的類編碼有什么問題。
謝謝您的幫助。
跟着這些步驟。
運行它except Exception, e: print repr(e)
。
看看你得到了什么例外。
將Exception
更改為您實際獲得的異常。
另外,請記住,異常e是一個對象。 您可以打印dir(e)
, e.__class__.__name__
等,以查看它具有的屬性。
此外,您可以在Python的>>>
提示符下以交互方式執行此操作。 然后你可以直接操縱對象 - 不要猜測。
你嘗試過這樣的事嗎?
try:
cursor.execute(some_statement)
except MySQLdb.IntegrityError, e:
# handle a specific error condition
except MySQLdb.Error, e:
# handle a generic error condition
except MySQLdb.Warning, e:
# handle warnings, if the cursor you're using raises them
我認為您要捕獲的異常是MySQLdb.ProgrammingError,並且要獲取有關它的信息,只需添加一個變量來存儲錯誤數據(元組),即:
try:
cursor.execute('DROP DATABASE IF EXISTS database_of_armaments')
except MySQLdb.ProgrammingError, e:
print 'There was a MySQL warning. This is the info we have about it: %s' %(e)
我設法捕獲這樣的mysql警告:
import _mysql_exceptions
try:
foo.bar()
except _mysql_exceptions.Warning, e:
pass
首先,您應該打開警告以視為異常,然后才能捕獲它們。 請參閱“錯誤”警告過濾器 - https://docs.python.org/3/library/warnings.html#the-warnings-filter
干凈利落
def log_warnings(curs):
for msg in curs.messages:
if msg[0] == MySQLdb.Warning:
logging.warn(msg[1])
cursor.execute('DROP DATABASE IF EXISTS database_of_armaments')
log_warnings(cursor)
msg [1]示例: - (u'Warning', 1366L, u"Incorrect integer value: '\\xa3' for column 'in_userid' at row 1")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.