简体   繁体   English

如何使用PyMySQL连接到数据库?

[英]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. 我正在使用Python创建数据库管理器,我希望用户能够选择数据库。

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? 如何判断connection是否连接到其他数据库? Or better yet, omit db and then add it later on. 或者更好的是,省略db然后再添加它。

Calling pymysql.connect actually creates the connection to the database. 调用pymysql.connect实际上会创建与数据库的连接。 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. 如果您希望稍后在代码中“重复使用”它,则可以将其分配给相同的变量名称。

Like this: 像这样:

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

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

You can just do: 你可以这样做:

connection.close()

And then open another connection. 然后打开另一个连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM