我正在编写一个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
Run Code Online (Sandbox Code Playgroud)
我的问题是......这是最好的做法吗?我应该在我的函数中重用我的光标吗?例如.哪个更好...
def callsANewCursorAndConnectionEachTime():
result1 = getDatabaseResult(someQuery1)
result2 = getDatabaseResult(someQuery2)
result3 = getDatabaseResult(someQuery3)
result4 = getDatabaseResult(someQuery4)
Run Code Online (Sandbox Code Playgroud)
或者完全取消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()
Run Code Online (Sandbox Code Playgroud)
Mat*_*yra 20
MySQLdb开发人员建议构建一个特定于应用程序的API,为您执行数据库访问,这样您就不必担心应用程序代码中的mysql查询字符串.它会使代码更具扩展性(链接).
至于游标,我的理解是最好的方法是为每个操作/事务创建一个游标.因此某些check value -> update value -> read value类型的事务可以使用相同的游标,但是对于下一个事务,您将创建一个新的事务.这再次指出了为db访问构建内部API的方向,而不是使用泛型executeSql方法.
还要记得关闭游标,并在查询完成后提交对连接的更改.
但是,您的getDatabaseResult函数不需要为每个单独的查询连接.只要您对游标负责,您就可以共享查询之间的连接.