[英]Loop stops after first Cursor.execute()
使用 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
看来您在 select 语句中的语法不正确,应该是:
select_stmt_XLS = 'SELECT * from ' + tbl_name + ''
我仍然不知道为什么循环在我原来的问题中停止,但我重写了代码以实现我的目标。
新代码可以:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.