python导入非本地mysql
时间: 2023-07-06 17:04:31 浏览: 22
如果要在Python中连接远程MySQL数据库,需要使用Python MySQL连接器。常用的Python MySQL连接器有两个:MySQL Connector/Python和PyMySQL。
MySQL Connector/Python是由MySQL官方提供的Python库,可用于连接MySQL数据库。而PyMySQL是一个纯Python实现的MySQL客户端库,也可以用于连接MySQL数据库。
以下是连接远程MySQL数据库的示例代码:
使用MySQL Connector/Python:
```python
import mysql.connector
# 连接MySQL数据库
cnx = mysql.connector.connect(user='username', password='password',
host='remote_host',
database='database_name')
# 执行查询
cursor = cnx.cursor()
query = ("SELECT * FROM table_name")
cursor.execute(query)
# 处理查询结果
for row in cursor:
print(row)
# 关闭连接
cursor.close()
cnx.close()
```
使用PyMySQL:
```python
import pymysql
# 连接MySQL数据库
cnx = pymysql.connect(host='remote_host', port=3306,
user='username', password='password',
db='database_name')
# 执行查询
cursor = cnx.cursor()
query = ("SELECT * FROM table_name")
cursor.execute(query)
# 处理查询结果
for row in cursor:
print(row)
# 关闭连接
cursor.close()
cnx.close()
```
其中,`remote_host`是远程MySQL服务器的IP地址或主机名,`username`和`password`是连接MySQL数据库所需的用户名和密码,`database_name`是要连接的数据库名称。
相关推荐


















