我不熟悉编程,所以如果下面程序中的逻辑没有意义,这可能就是原因。幸运的是,下面的代码运行并完成了我需要的所有事情,但感觉执行起来需要很长时间(每10000条记录需要6分钟)。在
该程序的目的是为数据库中的记录分配新的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