我幾乎沒有使用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