python - Best practice for database connection in recursive function? -
i have recursive python function processes data , needs write data mysql database within function.
i typically connect mysql db this
def myfunc(x, y): conn = mysql.connector.connect( user = "myuser", password = "supersecretpassword", host = "127.0.0.1", database = "mydatabase") # process data here, write db cursor = conn.cursor() cursor.execute("insert table a, b, c values(1,2,3)") conn.commit() myfunc(x, y)
while works, if within function, going create hundreds, if not thousands, of connections mysql database depending on how deep recursion goes within data processing. seems bad idea.
i tried creating connection , cursor in main part of code, outside of function, , referenced them within function global variable:
global cursor.execute("insert table a, b, c values(1,2,3)") global conn.commit()
but didn't work.
is possible write database in python within recursive function , open 1 connection db?
why don't keep single connection in python module, e.g.:
# script.py conn = mysql.connector.connect( user = "myuser", password = "supersecretpassword", host = "127.0.0.1", database = "mydatabase") def myfunc(x, y): # process data here, write db cursor = conn.cursor() cursor.execute("insert table a, b, c values(1,2,3)") conn.commit() myfunc(x, y)
Comments
Post a Comment