5

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)

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You can setup a dictionary to store your connections objects

db_dict = {}
for NAME from list_of_names:
   db_dict[NAME] = MySQLdb.connect('localhost', 'name', 'pwrd', NAME)

Then you can access the db using the dictionary or assign a local to also point to the connection.

current_db = db_dict['db_name']

Comments

0

I mostly use lambdas for a quicker approach (quick in the sense of writing the code, also it feels more pythonic).

db = lambda(db): MySQLdb.connect(host="127.0.0.1",user="user",passwd="pwd",db=db)

Then you can simply access the database by:

mydb = db("MyDb")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.