我应该重新使用游标对象还是使用 mysql.connector 创建一个新游标对象?

mev*_*303 9 mysql-connector mysql-python python-3.x

我应该重用游标对象还是为每个查询创建一个新游标对象?

重新使用光标:

    # we're going to connect to s3 and mysql
    db = mysql_connect(host="localhost",
                       user="user",
                       passwd="pass",
                       database="db")

    # Reusing the cursor
    cursor = db.cursor()

    # loop through all the files in the bucket one by one
    for key in bucket.get_all_keys():

        # the document id is the filename in the s3 bucket
        doc_id = key.name.split("/")[-1]
        cursor.execute("SELECT document_name FROM laws_docs WHERE id = %i", (doc_id,))
        doc_name = cursor.fetchone()[0]

    cursor.close()
Run Code Online (Sandbox Code Playgroud)

- 或者 -

每次新光标:

    # we're going to connect to s3 and mysql
    db =  mysql_connect(host="localhost",
                       user="user",
                       passwd="pass",
                       database="db")

    # loop through all the files in the bucket one by one
    for key in bucket.get_all_keys():

        # new cursor
        cursor = db.cursor()

        # the document id is the filename in the s3 bucket
        doc_id = key.name.split("/")[-1]
        cursor.execute("SELECT document_name FROM laws_docs WHERE id = %i", (doc_id,))
        doc_name = cursor.fetchone()[0]

         ursor.close()
Run Code Online (Sandbox Code Playgroud)

这还重要吗?该循环将至少运行 50,000 次。

小智 9

如果您使用MySQL Connector/Pythoncursor = db.cursor()将创建一个新CMySQLCursor实例(或者MySQLCursor如果您使用纯 Python 版本)。因此,对于第二个示例,您将创建 50,000 个游标实例。

您只需要一个光标。在循环外打开和关闭光标for(使用您的第一个示例)。