我是编程新手,所以如果以下程序中的逻辑没有意义,那可能就是为什么。幸运的是,下面的代码运行并完成了我需要的一切,但感觉执行需要很长时间(每10,000条记录需要6分钟)。有没有办法加快这个python程序? (short)
该程序的目的是为我的数据库中的记录分配新的ID,并允许用户指定增量值和这些ID的起点。
说实话,我并不完全确定执行时间是否不合理,因为我没有很多经验来建立它,但如果有一种方法来加速它,我是所有的耳朵。
# generates study IDs for MS Access dataset
import pyodbc
import random
import time
startTime = time.time()
dbFile = 'C:\Backend.accdb'
conn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
+ 'DBQ=' + dbFile + '; Provider=MSDASQL;')
cursor = conn.cursor()
# shuffle the existing IDs so the assignment of the new IDs is random
a = []
sql = "SELECT ID FROM Clients"
for row in cursor.execute(sql):
a.append(row.ID)
print "\nIDs appended to list...\n"
random.shuffle(a)
print "\nlist shuffled\n"
# assign new IDs according to the conditions below
startPt = 900001
increment = 7
idList = {}
for i in a:
idList[i] = startPt
startPt += increment
# append new IDs to another table in the database
for j, k in idList.iteritems():
sql = "INSERT INTO newID values ('%s', '%s')" %(j,k)
cursor.execute(sql)
conn.commit()
# close connection
cursor.close()
conn.close()
# calculate, in seconds, the time the program took to execute
executionTime = str(time.time() - startTime)
print "completed. the program took %s seconds to execute." %executionTime
可能http://codereview.stackexchange.com会是一个更好的地方。 – 2012-03-23 22:30:09
您应该意识到字符串中的反斜杠会引入'转义序列',因此当您的行'dbFile ='C:\ Backend.accdb'工作时,如果反斜杠之后的第一个字符是r,t, n或其他一些字母。在单引号或双引号字符串中使用双反斜线,或使用原始字符串('r“c:\ thing”'),或使用正斜杠(即使在Windows上也可用作路径分隔符)。 – 2012-03-23 22:45:02
请参阅http://docs.python.org/library/profile.html,但可能只是在关闭连接之前移动'conn.commit()'将会产生巨大的差异。 – agf 2012-03-23 22:58:50