我几乎没有使用Python和SQL的经验。为了完成我的硕士论文,我一直在自学。Python SQL查询执行时间
我只是写了一个小脚本基准约50个相同的结构化数据库,如下:
import thesis,pyodbc
# SQL Server settings
drvr = '{SQL Server Native Client 10.0}'
host = 'host_directory'
user = 'username'
pswd = 'password'
table = 'tBufferAux' # Found (by inspection) to be the table containing relevant data
column = 'Data'
# Establish a connection to SQL Server
cnxn = pyodbc.connect(driver=drvr, server=host, uid=user, pwd=pswd) # Setup connection
endRow = 'SELECT TOP 1 ' + column + ' FROM [' # Query template for ending row
with open(thesis.db_metadata_path(),'w') as file:
for db in thesis.db_list():
# Prepare queries
countRows_query = 'SELECT COUNT(*) FROM [' + db + '].dbo.' + table
firstRow_query = endRow + db + '].dbo.' + table + ' ORDER BY ' + column + ' ASC'
lastRow_query = endRow + db + '].dbo.' + table + ' ORDER BY ' + column + ' DESC'
# Execute queries
N_rows = cnxn.cursor().execute(countRows_query).fetchone()[0]
first_row = cnxn.cursor().execute(firstRow_query).fetchone()
last_row = cnxn.cursor().execute(lastRow_query).fetchone()
# Save output to text file
file.write(db + ' ' + str(N_rows) + ' ' + str(first_row.Data) + ' ' + str(last_row.Data) + '\n')
# Close session
cnxn.cursor().close()
cnxn.close()
我惊讶地发现,这个简单的程序采取近10秒的运行,所以我在想,如果这是正常的,或者我有我的代码的任何部分,可能会延缓执行。 (我提醒你,进行循环运行仅56倍)
注意,从thesis
(定制)模块的所有功能,具有非常小的影响,因为所有的人都只是变量赋值(除了thesis.db_list()
这是一个快速.TXT文件阅读)
编辑:This是由该程序生成的输出.txt文件。第二列是每个数据库的该表的记录数。
作为一个附注,你的列名在'first_row/last_row.Data'中被硬编码。使用'getattr(first_row,column)'来避免这种情况。 – 2015-02-08 01:48:50
您正在使用的索引顺序列?如果不是,则可能需要很长时间才能找到第一行和最后一行。 – 2015-02-08 05:33:03
@ivan_pozdeev好的!我没有注意到这一点。谢谢。 – POliveira 2015-02-08 11:30:37