我应该在Python MySQLdb模块中重用游标吗

27 投票
1 回答
20958 浏览
提问于 2025-04-17 06:08

我正在写一个Python的CGI脚本,用来查询MySQL数据库。我使用的是MySQLdb模块。因为这个数据库会被多次查询,所以我写了这个函数……

def getDatabaseResult(sqlQuery,connectioninfohere):
    # connect to the database
    vDatabase = MySQLdb.connect(connectioninfohere)
    # create a cursor, execute and SQL statement and get the result as a tuple
    cursor = vDatabase.cursor()
    try:
        cursor.execute(sqlQuery)
    except:
        cursor.close()
        return None
    result = cursor.fetchall()
    cursor.close()
    return result

我的问题是……这样做算是最佳实践吗?还是说我应该在我的函数中重复使用我的游标?比如,哪种方式更好……

def callsANewCursorAndConnectionEachTime():
    result1 = getDatabaseResult(someQuery1)
    result2 = getDatabaseResult(someQuery2)
    result3 = getDatabaseResult(someQuery3)
    result4 = getDatabaseResult(someQuery4)

或者干脆不使用getDatabaseeResult这个函数,直接做一些像……

def reusesTheSameCursor():
    vDatabase = MySQLdb.connect(connectionInfohere)
    cursor = vDatabase.cursor()

    cursor.execute(someQuery1)
    result1 = cursor.fetchall()

    cursor.execute(someQuery2)
    result2 = cursor.fetchall()

    cursor.execute(someQuery3)
    result3 = cursor.fetchall()

    cursor.execute(someQuery4)
    result4 = cursor.fetchall()

1 个回答

24

MySQLdb的开发者建议你建立一个专门的应用程序接口,这样可以帮你处理数据库访问的事情,这样你就不用在应用代码中担心那些mysql查询字符串了。这样做会让你的代码更容易扩展(链接)。

关于游标,我的理解是最好为每个操作或事务创建一个游标。比如说,有一个 检查值 -> 更新值 -> 读取值 的事务可以使用同一个游标,但下一个事务就应该创建一个新的游标。这又一次强调了建立一个内部API来处理数据库访问,而不是使用一个通用的 executeSql 方法。

另外,记得在查询完成后关闭你的游标,并提交对连接的更改。

不过,你的 getDatabaseResult 函数不需要为每个单独的查询都建立一个连接。只要你对游标的使用负责,就可以在查询之间共享连接。

撰写回答