我测试了一些pyodbc代码,当我人为地约束查询以返回较小的集合/运行得更快时,工作得很好。但是当我尝试运行w / o人工约束时,我开始遇到错误。 这是一个例子:
import pyodbc
#use only two days worth of data to artificially return a small sample
sql = """
select * into #T1 from MYTABLE where date between '11/1/2015' and '11/2/2105'
"""
#create a connection
cnxn = pyodbc.connect('DSN=MyDatabase')
#create a cursor
cursor = cnxn.cursor()
#execute SQL
cursor.execute(sql)
#close the cursor
cursor.close()
#commit changes
cnxn.commit()
#now prepare to read T1
sql2 = ("""SELECT * FROM #T1""")
#create a cursor
cursor = cnxn.cursor()
#execute SQL to extract data
cursor.execute(sql2)
cursor.fetchone() #returns data as expected
现在我只需通过更改日期范围来修改初始sql。初始cursor.execute(sql)运行时间更长,当我执行sql2时出现错误:
sql = """
select * into #T1 from MYTABLE where date between '1/1/2014' and '11/2/2105'
"""
#same code as in previous example
...
sql2 = ("""SELECT * FROM #T1""")
#create a cursor
cursor = cnxn.cursor()
#execute SQL to extract data
cursor.execute(sql2)
Traceback (most recent call last):
File "<ipython-input-85-939a3a2fefc6>", line 6, in <module>
cursor.execute(sql2)
ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name '#T1'. (208) (SQLExecDirectW)")
似乎连接已关闭。快速查询永远不会发生这种情况。