用生成器替换函数只会导致一次迭代

Replacing function with a generator results in only one iteration

以下代码打印 Access 数据库中的所有 table 和列名称:

import pyodbc

conn_str = (
    r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
    r'DBQ=O:\MAP_Reporting18_MAPDB_NewServer_Playground.accdb;'
    r'PWD=L56dx09b2syijhr;'
    r'UID=repMAP;'
    )
cnxn = pyodbc.connect(conn_str)
cursor = cnxn.cursor()

table_names = [table_info.table_name for table_info in cursor.tables()]
table_names_gen = (table_info.table_name for table_info in cursor.tables())

for table_name in table_names:
    print(f'TABLE NAME: {table_name}')
    for row in cursor.columns(table=table_name):
        print(f'    COLUMN NAME: {row.column_name}')

但是,如果 - 为了提高效率 - 我将 for table_name in table_names 替换为 for table_name in table_names_gen,它会起作用,它只会打印第一个 table 名称及其列的名称。

可能是什么原因?

您的 table_names_gen 生成器正在使用名为 cursor 的 Cursor 对象,并且当您遍历该生成器的结果时,您也在使用 cursor 对象来检索列名称,从而破坏 cursor 对象的状态并阻止生成器继续。您的生成器需要自己的 Cursor 对象,例如

table_names_gen = (table_info.table_name for table_info in cnxn.cursor().tables())