通过PYODBC检索行

时间:2014-07-07 14:50:03

标签: python 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'

在第一个代码中,它完全正常。在第二个中,我得到了上面的错误。

1 个答案:

答案 0 :(得分: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

代码效率低下。可能没用。