Mounarajan Mounarajan - 5 months ago 16
MySQL Question

can i reuse mysql connections for 2 functions in python

How can I reuse MySQL connections for two different functions in Python?

My current script is like this:

DATABASE_HOST = "xxx"
DATABASE_USER = "xxx"
DATABASE_PASSWORD = "xx"
DATABASE_NAME = "xxx"


def a(r):

db = MySQLdb.connect(DATABASE_HOST,DATABASE_USER,DATABASE_PASSWORD,DATABASE_NAME,charset='utf8',use_unicode=True)

cursor1 = db.cursor()

search = "***"
res_f = cursor1.execute(search)
data = cursor1.fetchone()
data = str(data)
data2 = data
'''to do'''

db.close()


def data_base(increment_count):

db = MySQLdb.connect(DATABASE_HOST,DATABASE_USER,DATABASE_PASSWORD,DATABASE_NAME,charset='utf8',use_unicode=True)

cursor1 = db.cursor()

search = "***"

res1 = cursor1.execute(search)

res2_1 = cursor1.fetchall()

get_urls1(res2_1)

increment_count = increment_count + 1
return increment_count


def get_urls1(res2):
for r in res2:
a(r)
print "Final Update Completed"

localtime = time.asctime( time.localtime(time.time()) )
print localtime


if __name__ == '__main__':
increment_count = 0
while increment_count < 1000000:
increment_count = data_base(increment_count)


Currently, for every
while
loop it is creating new connection for
data_base
and a function.

How could I reuse connections (either as function parameters or global variables)?

Answer

You can do either, pass as a function argument or use a global script variable. I think most would recommend avoiding global variables. This will only create one database connection.

if __name__ == '__main__':
    db = MySQLdb.connect(host=DATABASE_HOST, port=DATABASE_PORT, user=DATABASE_USER, passwd=DATABASE_PASSWORD, db=DATABASE_NAME)

    increment_count = 0
    while increment_count < 3:
        increment_count = data_base(increment_count, db)

then I would change the local name of your variable in the data_base function to avoid confusion and shadowing variable names with more scope (this isn't required you can keep the same name if desired). Your function would look like this

def data_base(local_increment_count, local_db): 

    cursor1 = local_db.cursor()

    # ***Rest of code here***

    # Pass db object to this function if you need
    get_urls1(res2_1, local_db)

    local_increment_count = local_increment_count + 1
    return local_increment_count

This is a nice article explaining variables and scope for Python

Comments