我想更新從CSV文件值的數據庫,下面是我的代碼:的Python MySQLdb的在更新緩慢值
import MySQLdb as mdb
import sys
import csv
con = None
command = ''
new_name_list = []
old_name_list = []
duplicates = []
update_list = []
file = 'csv_file.csv'
listReader = csv.reader(open(file, 'r'))
for row in listReader:
new_name_list.append(row)
try:
con = mdb.connect('localhost', 'root', 'mypassword', 'mydb')
con.autocommit(True)
cur = con.cursor()
cur.execute("SELECT fil_name FROM file WHERE fil_name like 'boy%' and fil_job_id=1")
numrows = int(cur.rowcount)
for i in range(numrows):
file_name = cur.fetchone()
old_name_list.append(file_name[0])
d = dict(new_name_list)
for n in old_name_list:
try:
print n + " has been updated to " + d[n]
command = "UPDATE file SET fil_name='" + d[n] + "' WHERE fil_name='" + n + "'"
cur.execute(command)
except KeyError:
duplicates.append(n)
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
finally:
if con:
con.close()
大約需要2-3秒的每個打印出現,這導致我認爲更新執行正在緩慢進行。我有很多值需要更新,這不應該是它應該執行的速度(假設我能夠快速打印所有d[n]
的值)
有沒有辦法加快更新?
編輯:數據庫採用InnoDB引擎
你確定它每循環運行2-3秒,而不僅僅是緩慢地刷新sys.stdout嗎?您是否在每次打印語句後嘗試添加'sys.stdout.flush()'? – jdi