[英]Python Peewee MySQL bulk update
我正在使用Python 2.7,Peewee和MySQL。 如果csv中存在订单号,则我的程序将从csv文件读取并更新该字段。 可能会有2000-3000次更新,而我使用的是幼稚的方法来逐一更新记录,这实在太慢了。 我已经从使用Peewee更新转移到Raw查询,这有点快。 但是,它仍然很慢。 我想知道如何在不使用循环的情况下以更少的事务更新记录。
def mark_as_uploaded_to_zoho(self, which_file):
print "->Started marking the order as uploaded to zoho."
with open(which_file, 'rb') as file:
reader = csv.reader(file, encoding='utf-8')
next(reader, None) ## skipping the header
for r in reader:
order_no = r[0]
query = '''UPDATE sales SET UploadedToZoho=1 WHERE OrderNumber="%s" and UploadedToZoho=0''' %order_no
SalesOrderLine.raw(query).execute()
print "->Marked as uploaded to zoho."
您可以为此使用insert_many来限制事务数量并大大提高速度。 这需要迭代器返回“模型”字段与字典键匹配的字典对象。
根据要插入的记录数,您可以一次完成所有记录,也可以将其分成较小的块。 过去,我一次插入了10,000多个记录,但这可能会非常慢,具体取决于数据库服务器和客户端规格,因此我将展示两种方式。
with open(which_file, 'rb') as file:
reader = csv.DictReader(file)
SalesOrderLine.insert_many(reader)
要么
# Calls a function with chunks of an iterable as list.
# Not memory efficient at all.
def chunkify(func, iterable, chunk_size):
chunk = []
for o in iterable:
chunk.append(o)
if len(chunk) > chunk_size:
func(chunk)
chunk = []
with open(which_file, 'rb') as file:
reader = csv.DictReader(file)
chunkify(SalesOrderLine.insert_many, reader, 1000)
有关“批量化”迭代器的更有效方法,请查看此问题 。
只需在此处概述with db.atomic
使用with db.atomic
可以进一步提高速度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.