【发布时间】:2021-12-12 04:27:37
【问题描述】:
我有下面的代码,它从一个表中选择一些数据,在另一个表中查找相关数据,更新相关表中的数据并从第一个表中删除数据。使用works下方的游标但不确定是best。我需要像这样每次都定义一个新的 cursor(x) = db.cursor() 吗?
db = MySQLdb.connect(host=cred.host, user=cred.user, password=cred.password,
db=cred.db, port=cred.port)
cursor = db.cursor()
cursor.execute("SELECT * FROM tbl_sqs order by timeOfOfferChange ASC limit 200")
for reprice in cursor.fetchall():
#do initial processing of data retreived from tbl_sqs
#select the current value(s) from tbl_inventory_data that are for the same product from the same seller
cursor2 = db.cursor() # prepare a cursor object using cursor() method
cursor2 = db.cursor()
cursor2.execute("SELECT * FROM tbl_inventory_data WHERE `asin`=%s and `user`=%s", (ASIN, SellerId))
db.commit()
for row in cursor2.fetchall(): #iterate over inventory items
cursor3 = db.cursor() # prepare a cursor object using cursor() method#
cursor3.execute("UPDATE tbl_inventory_data SET `…..WHERE `seller-sku`=%s AND `user`=%s"))
db.commit()
cursor4 = db.cursor()
cursor4.execute("DELETE FROM tbl_sqs WHERE MessageId=%s", (message_id)) # delete the message just processed.
db.commit()
【问题讨论】:
-
不,您不需要每次都创建一个新游标,尽管创建一个游标并不是那么昂贵。只要完成,您就可以重复使用它们。例如,您不能在
for row in cursor2循环中重复使用cursor2。请注意,您绝对不需要在每次操作后都使用commit。这会让你慢下来。 -
你是对的。删除它会将处理 1000 条记录的时间从 70 秒从 128 秒更改为 128 秒
标签: python mysql database-cursor