【问题标题】:Python / MySQL - this use of cursors works but is it correct?Python / MySQL - 这种游标的使用有效,但它正确吗?
【发布时间】: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


【解决方案1】:

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

另外,使用完数据库后关闭游标就好了:

cursor.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    相关资源
    最近更新 更多