Reputation: 19
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.
Upvotes: 1
Views: 1500
Reputation: 7421
Like this:
connection1 = pymysql.connect(
host='localhost'
user='root'
passwd=''
db='my_database'
)
connection2 = pymysql.connect(
host=?
user=?
passwd=?
db='my_other_database'
)
Upvotes: 1
Reputation: 53
You can just do:
connection.close()
And then open another connection.
Upvotes: 0
Reputation: 43
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.
Upvotes: 2