Python, sharing mysql connection in multiple functions - pass connection or cursor?

泪湿孤枕 提交于 2021-01-27 02:51:57

问题


I am opening mysql connection in the main function and use that connection in multiple functions called by the main function.

Is there anything wrong with passing cursor from main function instead of passing the connection?

I.e.:

Pass in cursor from 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 ...')

Pass in connection from main function

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:


The answer comes from Law of Demeter: Pass cursor.

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



来源:https://stackoverflow.com/questions/31233570/python-sharing-mysql-connection-in-multiple-functions-pass-connection-or-curs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!