Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ...')
like image 339
Pavel Chernikov Avatar asked Jul 05 '15 18:07

Pavel Chernikov


People also ask

How do you pass the cursor in Python?

Pass in cursor from main functionconnect(...) with conn as cursor: func1(cursor) func2(cursor) conn. close() def func1(cursor): cursor. execute('select ...') def func2(cursor): cursor. execute('insert ...')

What are the four arguments of connect () in Python for connecting with MySQL?

connect() Method. Connects to a MySQL server. connect() supports the following arguments: host , user , password , database , port , unix_socket , client_flags , ssl_ca , ssl_cert , ssl_key , ssl_verify_cert , compress .

What is cursor in MySQL connector Python?

The MySQLCursor of mysql-connector-python (and similar libraries) is used to execute statements to communicate with the MySQL database. Using the methods of it you can execute SQL statements, fetch data from the result sets, call procedures.

How does Python manage database connection?

To create a connection between the MySQL database and Python, the connect() method of mysql. connector module is used. We pass the database details like HostName, username, and the password in the method call, and then the method returns the connection object.


1 Answers

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

like image 130
maaartinus Avatar answered Oct 10 '22 12:10

maaartinus