循环在第一个Cursor.Execute()之后停止第一个、Cursor、Execute

2023-09-03 10:29:03 作者:深知你是梦

使用pyodbc,我正在尝试循环访问Excel中的工作表,读取以字符串";约会&开始的工作表,然后将结果写入Access数据库中的现有表。

我能够遍历所有的工作表,并识别以约会和约会开头的工作表(有四个工作表--约会1、约会2等)。 我还可以读取找到的任何一个工作表上的数据,并且可以将结果写入DB表。 当我尝试在for循环中执行所有这些操作时,我能够获得所有的表名,但只要我执行()一条SELECT语句,循环就会停止。

易语言如何用循环依次读取多个编辑框的内容

它没有出错-print()语句工作,但循环在第二个print语句之后停止。如果我注释掉第二个print(),第一个打印将返回四个结果。

Cursor.commit()不会更改行为。

# execute select stmt
def select_xls_data(tbl_name):
    select_stmt_XLS = 'SELECT * from [' + tbl_name + ']'
    result_XLS = crsr_XLS.execute(select_stmt_XLS).fetchall()
    return result_XLS

# loop through XLS sheets
for table_info in crsr_XLS.tables():
    tbl_name = table_info.table_name
    if (tbl_name.startswith('Appointment')):
        print(tbl_name)  # will succesfully loop through all sheets
        print(select_xls_data(tbl_name))  # will only loop once

推荐答案

我仍然不知道我的原始问题中循环为什么停止,但我重写了代码以实现我的目标。

新代码执行以下操作:

遍历文件中的所有表并将感兴趣的表添加到列表 遍历创建的列表并对每个感兴趣的表执行SELECT语句 将每个选择的结果添加到结果列表
def select_xls_data(tbl_name):
    select_stmt_XLS = 'SELECT * from ' + tbl_name
    result_XLS = crsr_XLS.execute(select_stmt_XLS).fetchall()
    return result_XLS

# discover the tables of interest and write their names to a list
tables = []
for table_info in crsr_XLS.tables():
    tbl_name = table_info.table_name
    if (tbl_name.startswith('Appointment')): tables.append('['+tbl_name+']')

# loop through tables of interest, execute select stmt on each and append each result set to a list
results = []
for tbl_name in tables: results.append(select_xls_data(tbl_name))