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

时间:2019-05-04 23:03:40

标签: python-3.x mysql-python mysql-connector

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

重复使用光标:

    # 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()

-或-

每次都有新光标:

    # 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()

这有关系吗?该循环将至少运行50,000次。

1 个答案:

答案 0 :(得分:1)

如果您使用的是MySQL Connector/Python,则cursor = db.cursor()将创建一个新的CMySQLCursor实例(如果使用的是纯Python版本,则将创建MySQLCursor)。因此,对于第一个示例,您将创建50,000个光标实例。 您只需要一个光标。在for循环外部打开和关闭光标(使用第一个示例)。