什么时候关闭 MySQLdb 中的游标?

When to close a cursor in MySQLdb?

我有一个运行循环的程序,每次迭代运行一个 sql 查询。我目前将其实施为。

mysql_connection = MySQLdb.connect(...)
for record in records:
  cursor = mysql_connection.cursor()
  curson.execute(some_query)
  result = None
  for r in cursor:
       result = r
  cursor.close()
  #Do something with result
mysql_connection.close()

这会花费很多时间,因为每次循环运行时,都会创建一个新游标。将光标放在循环外是更好的方法还是我可以使用其他方法来提高性能。

我已经在索引列上进行了搜索查询,因此 mysql 方面的改进范围较小。

最好一次性创建游标。另请注意,您在循环中执行 return,因此您似乎只调用了一次 cursor.execute

尝试将 c.arraysize 设置为对您的用例有意义的值(其中 c 是光标),并将光标置于循环之外。查看此页面:http://mysql-python.sourceforge.net/MySQLdb.html#cursor-objects

If you wanted more rows, you could use c.fetchmany(n) or c.fetchall(). These do exactly what you think they do. On c.fetchmany(n), the n is optional and defaults to c.arraysize, which is normally 1. Both of these methods return a sequence of rows, or an empty sequence if there are no more rows. If you use a weird cursor class, the rows themselves might not be tuples.