2010-07-24 32 views
2

由於某種原因,每當我在db遊標上運行查詢時,它在.messages列表中會生成兩個錯誤,這是一個特性嗎?python mysqldb遊標消息列表顯示錯誤兩次

這裏是運行查詢的代碼,所有的應用程序是開放的數據庫連接,一旦與強制錯誤或許運行此,請閱讀.messages,然後退出

import MySQLdb 

class dbobject: 
    def __init__(self, dbhost, dbuser, dbpass, dbname): 
     self.connection = MySQLdb.connect(user=dbuser, passwd=dbpass, host=dbhost, db=dbname) 
     self.cursor = self.connection.cursor() 

    def try_query(self, query, args=()): 
     """ attempts to run a query, where 
       query is the query to be run, with '%s' statements where the values should be, and 
       args is a tuple of the values to go with the query""" 
     try: 
      if args ==(): 
       self.cursor.execute(query) 
      else: 
       self.cursor.execute(query, args) 
      self.connection.commit() 
     except: 

      self.connection.rollback() 

    def add_unit(self, name, version, credits): 
     """ takes name, version, credits 
       name is the name of the unit paper 
       version is the unit version, and 
       credits is how many credits its worth""" 
     self.try_query("insert into dsfdf tbl_unit (unit_name, unit_version, unit_credits) values (%s,%s,%s)",(name,version,credits)) 

    def close(self): 
     self.cursor.close() 
     self.connection.close() 


blah = dbobject(#####################) 
blah.add_unit("thing", "something", 6) 
for i in blah.cursor.messages: 
    print i 
blah.close() 

回答

1

可以張貼您收到的訊息。

mysql_insert_etc.py:22:警告:數據 截斷爲列 'VAL' 在行1個
self.cursor.execute(查詢,參數) (, ( '警告',1265L,「數據截短爲 列 'VAL' 在行1" ))

從以上(製造誤差)似乎MySQLdb的返回:

  1. MySQL的警告,並
  2. 它自己的例外。

使用下面的代碼可以抑制警告,或讓他們引發異常。

引發一個異常(從this example略有修改):

from warnings import catch_warnings, simplefilter 

def try_query(self, query, args=()): 
    with catch_warnings(): 
     simplefilter('error', MySQLdb.Warning) 
     try: 
      if args ==(): 
       self.cursor.execute(query) 
      else: 
       self.cursor.execute(query, args) 
      self.connection.commit() 
     except MySQLdb.Error, e: 
      self.connection.rollback() 
      raise e 

禁止警告from here):

from warnings import filterwarnings 

filterwarnings('ignore', category=MySQLdb.Warning) 
+0

謝謝,最終被試圖讓不正確的查詢錯誤日誌,並且使用異常中的信息代替,應該早一點想到 – biokiwi 2010-07-24 06:25:20