1. 安装MySQL Connector/Python模块:您可以使用pip命令来安装MySQL Connector/Python模块,命令如下:
pip install mysql-connector-python
2. 导入MySQL Connector/Python模块:文章源自网吧系统维护-https://www.58pxe.com/11104.html
import mysql.connector
3. 建立与数据库的连接:文章源自网吧系统维护-https://www.58pxe.com/11104.html
# 配置数据库连接信息
config = {
'host': '远程主机地址',
'port': 3306, # MySQL默认端口
'user': '用户名',
'password': '密码',
'database': '数据库名',
'charset': 'utf8' # 数据库编码,根据实际情况设置
}
# 建立数据库连接文章源自网吧系统维护-https://www.58pxe.com/11104.html
cnx = mysql.connector.connect(**config)
在`config`字典中,您需要填写远程主机地址、用户名、密码、数据库名等信息。文章源自网吧系统维护-https://www.58pxe.com/11104.html
4. 创建游标对象并执行SQL语句:文章源自网吧系统维护-https://www.58pxe.com/11104.html
# 创建游标对象文章源自网吧系统维护-https://www.58pxe.com/11104.html
cursor = cnx.cursor()
# 执行SQL查询文章源自网吧系统维护-https://www.58pxe.com/11104.html
query = "SELECT * FROM 表名" cursor.execute(query)
# 获取查询结果文章源自网吧系统维护-https://www.58pxe.com/11104.html
result = cursor.fetchall()
# 输出查询结果文章源自网吧系统维护-https://www.58pxe.com/11104.html
for row in result:
print(row)
# 关闭游标文章源自网吧系统维护-https://www.58pxe.com/11104.html
cursor.close()
5. 关闭数据库连接:文章源自网吧系统维护-https://www.58pxe.com/11104.html
cnx.close()
通过上述步骤,您就可以在Python中实现与异地的MySQL数据库的连接和操作。请确保提供正确的数据库连接信息以及具备访问远程数据库的权限。文章源自网吧系统维护-https://www.58pxe.com/11104.html 文章源自网吧系统维护-https://www.58pxe.com/11104.html


评论