5

I am trying to update a database with values from a csv file, the following is my code:

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()

It takes about 2-3 seconds for each print to appear, which leads me to think that the update execution is being made slowly. I have a lot of values to update and this should not be the speed that it should be executing (given that I was able to get a quick printout of all the values of d[n] )

Is there anyway to speed up the updating?

EDIT: The database is using InnoDB engine

4

2 回答 2

8

您可以尝试使用executemany

data = [(n, d[n]) for n in old_name_list]
cur.executemany("UPDATE file SET fil_name='%s'  WHERE fil_name='%s'", data)

此外,您可能需要考虑对 fil_name 进行索引(假设 fil_name 是只读的)

于 2012-06-14T01:20:56.777 回答
3

根据您的描述,每次打印需要 2~3 秒,所以我认为问题可能在于:

  1. 你有索引表文件的 fil_name 列吗?
  2. 您使 auto_commit 为真,每次更新都是提交的事务。

如果情况是 1,只需在该列上创建索引,不要在更新时进行表扫描。

如果情况是 2,@dave 给出了一个很好的答案。

于 2012-06-14T02:18:34.730 回答