Python / MySQL - 这种游标的使用有效,但是否正确?

Python / MySQL - this use of cursors works but is it correct?

我有下面的代码,它从一个 table 中选择一些数据,在另一个 table 中找到相关数据,更新相关 table 中的数据并从第一个中删除数据table。 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()

您不需要在每次查询时都为数据库创建游标。最好创建一次游标并使用同一个游标,直到使用数据库结束。每个游标创建都会对数据库产生开销,在大型或繁忙的数据库中可能会导致一些问题。

此外,在使用完数据库后关闭游标是好的:

cursor.close()