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

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -