Search code examples
pythondatabasepymysql

How can I connect to a database using PyMySQL?


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.


Solution

  • Like this:

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