通过PYODBC获取行

0 投票
1 回答
601 浏览
提问于 2025-04-18 12:21

我现在在代码上遇到了一些问题。一方面,我有一段可以正常工作的代码,但我觉得可以进一步改进。不过,我尝试优化代码的结果却很糟糕。以下是我原来的代码:

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

通过做以下更改解决了问题:

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

这个代码效率不高,可能没什么用。

撰写回答