【问题标题】:Loop stops after first Cursor.execute()循环在第一个 Cursor.execute() 之后停止
【发布时间】:2021-01-07 23:52:42
【问题描述】:

使用 pyodbc,我正在尝试遍历 Excel 中的工作表,读取以字符串“Appointment”开头的工作表,然后将结果写入 Access DB 中的现有表中。

我能够遍历所有工作表并确定以“约会”开头的工作表(其中有四个 - Appointment1、Appointment2 等)。 我还可以读取找到的任何一张表上的数据,并将结果写入数据库表。 当我尝试在 for 循环中执行所有这些操作时,我能够获取所有工作表名称,但是一旦我执行()一个 select 语句,循环就会停止。

它不会出错 - print() 语句有效,但循环在第二个 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

【问题讨论】:

    标签: python excel ms-access pyodbc


    【解决方案1】:

    您的 select 语句中的语法似乎不正确,应该是:

    select_stmt_XLS = 'SELECT * from ' + tbl_name + ''
    

    【讨论】:

    • 谢谢,但是语法是正确的,结果是SELECT * from [Appointment1$],或者2$等等。
    【解决方案2】:

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

    新代码:

    1. 遍历文件中的所有表并将感兴趣的表添加到列表中
    2. 遍历创建的列表并为每个感兴趣的表执行一个选择语句
    3. 将每个选择的结果添加到结果列表中
    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))
    

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      相关资源
      最近更新 更多