2014-07-07 55 views
0

我現在用我的代碼有一些問題。一方面,我的代碼可行,但我認爲我可以改進。然而,我試圖完善代碼已經是......災難性的。這是我的原始代碼:通過PYODBC檢索行

overall_list = [] 
customer_list = [] 
if remote_system_id == 'hibiscus' or remote_system_id is None: 
    hibiscus_cursor.execute(hibiscus_full_SQLstring, hibiscus_parameters) 
    row = hibiscus_cursor.fetchone() 
    resultCounter = 0 
    while row and resultCounter < remote_system_max_results: 
     customer_list.append({'Hibiscus Customer Number': str(row[0])}) 
     row = hibiscus_cursor.fetchone() 
     resultCounter += 1 
    overall_list.append(customer_list) 

customer_list = [] 
if remote_system_id == 'coxcomb' or remote_system_id is None: 
    coxcomb_cursor.execute(coxcomb_full_SQLstring, coxcomb_parameters) 
    row = coxcomb_cursor.fetchone() 
    resultCounter = 0 
    while row and resultCounter < remote_system_max_results: 
     customer_list.append({'Coxcomb Customer Number': str(row[0])}) 
     row = coxcomb_cursor.fetchone() 
     resultCounter += 1 
    overall_list.append(customer_list) 

上面的代碼是有效的,但我被告知要稍微改進它。具體來說,我有兩個獨立的例程來生成輸出。有人告訴我,它結合起來,但結果並不有利:以上

customer_list = [] 
hibiscus_cursor.execute(hibiscus_full_SQLstring, hibiscus_parameters) 
coxcomb_cursor.execute(coxcomb_full_SQLstring, coxcomb_parameters) 
row = coxcomb_cursor.fetchone() 
resultCounter = 0 
while row and resultCounter < remote_system_max_results: 
    customer_list.append({'Hibiscus Customer Number': str(row[0])}) 
    row = coxcomb_cursor.fetchone() 
    customer_list.append({'Coxcomb Customer Number': str(row[0])}) 
    row = hibiscus_cursor.fetchone() 
    resultCounter += 1 

的代碼是我嘗試完善它,但沒有很好的效果。爲什麼我得到這樣的錯誤任何想法:

customer_list.append({'Coxcomb Customer Number': str(row[0])}) 
TypeError: 'NoneType' object has no attribute '__getitem__' 

編輯:

多一點信息。這是兩個獨立的數據庫,並且完全沒有關係。他們唯一可能的關係是他們都包含客戶信息。連這樣的:

cnxn = pyodbc.connect(HIBISCUS_CONNECTION) 
hibiscus_cursor = cnxn.cursor() 

cnxn = pyodbc.connect(COXCOMB_CONNECTION) 
coxcomb_cursor = cnxn.cursor() 

我查詢這兩個數據庫,而且我希望能找到這樣的:

WHERE firstname LIKE 'adam' 

在第一個代碼,它完美的罰款。在第二個,我得到上面的錯誤。

回答

0

通過使這些變化修正它:

customer_list = [] 
hibiscus_cursor.execute(hibiscus_full_SQLstring, hibiscus_parameters) 
coxcomb_cursor.execute(coxcomb_full_SQLstring, coxcomb_parameters) 
row = hibiscus_cursor.fetchone() 
row2 = coxcomb_cursor.fetchone() 
resultCounter = 0 
while (row or row2) and resultCounter < remote_system_max_results: 
    if hibiscus_cursor.fetchone() is not None: 
     customer_list.append(str(row[0])) 
     row = hibiscus_cursor.fetchone() 
    if coxcomb_cursor.fetchone() is not None: 
     customer_list.append(str(row2[0])) 
     row2 = coxcomb_cursor.fetchone() 
    resultCounter += 1 

代碼是低效的。可能沒有用處。