循环在第一个Cursor.Execute()之后停止 [英] Loop stops after first Cursor.execute()

查看:0
本文介绍了循环在第一个Cursor.Execute()之后停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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

推荐答案

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

新代码执行以下操作:

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

这篇关于循环在第一个Cursor.Execute()之后停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆