Python,在多个函数中共享mysql连接 - 传递连接或游标?

时间:2015-07-05 18:23:50

标签: python mysql pymysql

我在main函数中打开mysql连接,并在main函数调用的多个函数中使用该连接。

从主函数传递游标而不是传递连接有什么问题吗?

即:

从主要功能传入光标

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 ...')

1 个答案:

答案 0 :(得分:4)

答案来自Law of Demeter:传递光标。

这也会导致代码略短。在这种情况下,它非常简单,但有时它可能很多(例如,传递数据库名称与传递游标)。