2009-11-24 49 views
0

我有一個從CSV文件更新MySQL表的函數。 MySQL表包含客戶端帳號 - 這是我用來與CSV文件進行比較的。在某些情況下,某些查詢將失敗,因爲從CSV文件比較的帳號尚未添加。在MySQLdb上捕獲更新錯誤

如何從更新過程中失敗的CSV文件中獲取記錄?我想將這些記錄存儲在一個單獨的文件中,然後再重新讀取該文件,直到所有記錄都成功更新。

以下是更新數據庫的功能。

def updateDatabase(records, options): 
    """Update database""" 
    import re # Regular expression library 
    import MySQLdb 

    # establish DB connection 
    try: 
     db = MySQLdb.connect(host="localhost", user="root", passwd="", db="demo") 
    except MySQLdb.Error, e: 
     print "Error %d: %s" % (e.args[0], e.args[1]) 
     sys.exit (1) 
    # create cursor 
    cursor = db.cursor() 
    # tell MySQLdb to turn off auto-commit 
    db.autocommit(False) 

    # inform the user that this could take a while 
    if len(records) > 499: 
     print 'This process can take a while.' 

    print 'Updating the database now...' 
    # this is the actual loop 
    maxrecords = len(records) 
    for record in records: 
     account_no, ag_1to15, ag_16to30, ag_31to60, ag_61to90, ag_91to120, beyond_120, total, status, credit_limit = record 
     if re.match('1000', account_no): 
      query = """UPDATE sys_accountscf SET cf_581 = %s, cf_583 = %s, cf_574 = %s, cf_575 = %s, cf_576 = %s, cf_577 = %s, cf_579 = %s, cf_585 = '%s', cf_558 = %s WHERE cf_538 = %s""" 
     else: 
      query = """UPDATE sys_accountscf SET cf_580 = %s, cf_582 = %s, cf_568 = %s, cf_569 = %s, cf_571 = %s, cf_572 = %s, cf_578 = %s, cf_584 = '%s', cf_555 = %s WHERE cf_535 = %s""" 
     cursor.execute(query % (ag_1to15, ag_16to30, ag_31to60, ag_61to90, ag_91to120, beyond_120, total, status, credit_limit, account_no)) 
    # commit all changes and close database connection  
    try: 
     db.commit() 
    except: 
     db.rollback() 
    cursor.close() 
    db.close() 

回答

1

更新查詢返回受影響的行數。 執行執行後檢查Cursor.rowcount將給出該編號。如果不是1,那個更新行失敗。

+0

即使將autocommit設置爲false,這個工作是否會起作用? – Francis 2009-11-24 07:33:36