Cole Cole - 2 months ago 9
Python Question

set up a MySQLdb connection object for multiple databases

This question is likely noobish.

Instead of hardcoding the MySQLdb connection object: e.g,

db = MySQLdb.connect('localhost','name','pwrd','db_name')


How do I set it up so I can specify the db_name (or any other part of the connection object) from a list or some other variable. E.g:

for NAME from list_of_names:
db = MySQLdb.connect('localhost', 'name', 'pwrd', NAME)

Answer

You could setup a function that would return a new database connection based on the name passed in.

def get_db_connection(database_name):
    return MySQLdb.connect('localhost', 'name', 'pwrd', database_name)

and then call get_db_connection whenever you needed to use a new database.

Better, you might try db.select_db('my_new_databasename') to switch from one database to another inside the same connection. This assumes db is your connection object from the MySQLdb.connect() call. This means you don't need to build a new connection each time.

Of note, creating database connections is expensive so try to avoid creating them and throwing them away at abandon.

Comments