Python中如何连接和断开MySQL数据库?
发布时间:2023-07-04 09:39:39
Python中可以使用Python标准库中的mysql.connector模块来连接和断开MySQL数据库。下面是一个使用Python连接和断开MySQL数据库的示例代码:
1. 导入mysql.connector模块:
import mysql.connector
2. 连接MySQL数据库:
# 创建连接
cnx = mysql.connector.connect(user='username', password='password',
host='hostname',
database='database_name')
其中,user和password分别是数据库的用户名和密码,host是数据库的主机名或IP地址,database是要连接的数据库名。
3. 关闭MySQL连接:
cnx.close()
完整的示例代码如下:
import mysql.connector
# 连接MySQL数据库
cnx = mysql.connector.connect(user='username', password='password',
host='hostname',
database='database_name')
# 执行数据库操作(例如查询、插入、更新等)
# 关闭MySQL连接
cnx.close()
在上述的示例代码中,我们首先导入了mysql.connector模块。然后,使用mysql.connector.connect()方法来连接MySQL数据库。这个方法的参数分别是数据库的用户名、密码、主机名和数据库名。成功连接后,我们可以执行一些数据库操作,比如查询、插入、更新等。最后,我们通过cnx.close()方法关闭了数据库连接。
通过以上的步骤,我们可以在Python中连接和断开MySQL数据库。这样就可以方便地在Python中进行MySQL数据库的操作了。
