我是编程新手,所以如果以下程序中的逻辑没有意义,那可能就是原因。幸运的是,下面的代码运行并完成了我需要它做的所有事情,但感觉它需要很长时间才能执行(每 10,000 条记录需要 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
请您参考如下方法:
# 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)
如果你想把所有东西都放在一个列表中,使用cursor.fetchall(),它会为你创建列表
print "\nIDs appended to list...\n"
random.shuffle(a)
print "\nlist shuffled\n"
您应该能够修改您的查询以便为您打乱它 SELECT ID FROM Clients ORDER BY RAND() 或类似的。这样您就不必自己进行洗牌,而且速度可能会更快。
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)
你几乎应该总是使用参数,而不是字符串格式
cursor.execute("INSERT INTO newID values(?,?)", (j, k))
这可以让您免受 SQL 注入(inject)攻击。您还可以使用 executemany 函数。它允许您传递不同参数的列表,并对其中的许多参数执行相同的查询。这可能是处理数据的最快方式。
conn.commit()
您不应该在每次插入后都提交。通常您会等到全部完成后再提交。
