Python,在多个函数中共享mysql连接——传递连接还是游标? [英] Python, sharing mysql connection in multiple functions - pass connection or cursor?
本文介绍了Python,在多个函数中共享mysql连接——传递连接还是游标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在 main 函数中打开 mysql 连接,并在 main 函数调用的多个函数中使用该连接.
I am opening mysql connection in the main function and use that connection in multiple functions called by the main function.
从主函数传递光标而不是传递连接有什么问题吗?
即:
从主函数传入光标
def main():
conn = pymysql.connect(...)
with conn as cursor:
func1(cursor)
func2(cursor)
conn.close()
def func1(cursor):
cursor.execute('select ...')
def func2(cursor):
cursor.execute('insert ...')
从主函数传入连接
def main():
conn = pymysql.connect(...)
func1(conn)
func2(conn)
conn.close()
def func1(conn):
with conn as cursor:
cursor.execute('select ...')
def func2(conn):
with conn as cursor:
cursor.execute('insert ...')
推荐答案
答案来自德米特法则:传递光标.
这也导致代码略短.在这种情况下,它非常简单,但有时可能很多(例如,传递数据库名称与传递游标).
This also leads to a slightly shorter code. In this case, it's pretty trivial, but sometimes it may be a lot (e.g., passing a database name vs. passing a cursor).
这篇关于Python,在多个函数中共享mysql连接——传递连接还是游标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文