1

I am making a database manager in Python and I want the user to be able to select a database.

I know that one can connect to a database using the following code

connection = pymysql.connect(
    host='localhost'
    user='root'
    passwd=''
    db='my_database'
)

But what if the user wants to connect to a different database later on? How would I tell connection to connect to a different database? Or better yet, omit db and then add it later on.

1
  • you probably should close previously opened one and create another connection Commented Jun 1, 2017 at 14:44

3 Answers 3

2

Calling pymysql.connect actually creates the connection to the database. If you want to connect to a different database you should create a new connection object, rather than trying to reuse the same one. You could assign it to the same variable name if you wanted to 'reuse' it later in your code.

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

Comments

1

Like this:

connection1 = pymysql.connect(
    host='localhost'
    user='root'
    passwd=''
    db='my_database'
)

connection2 = pymysql.connect(
    host=?
    user=?
    passwd=?
    db='my_other_database'
)

Comments

0

You can just do:

connection.close()

And then open another connection.

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.