pymysql sshtunnel 连接阿里云MySQL数据库
时间: 2023-10-27 22:06:13 浏览: 52
连接阿里云MySQL数据库需要进行以下步骤:
1. 安装pymysql和sshtunnel模块
```python
pip install pymysql
pip install sshtunnel
```
2. 导入模块
```python
import pymysql
from sshtunnel import SSHTunnelForwarder
```
3. 配置SSH隧道
```python
ssh_host = 'xxx.xxx.xxx.xxx' # 云服务器的IP地址
ssh_port = 22 # 云服务器的SSH端口
ssh_user = 'root' # 云服务器的SSH用户名
ssh_password = 'xxxxxx' # 云服务器的SSH密码
with SSHTunnelForwarder(
(ssh_host, ssh_port), # 云服务器的SSH地址和端口
ssh_username=ssh_user,
ssh_password=ssh_password,
remote_bind_address=('localhost', 3306) # MySQL服务器的地址和端口
) as tunnel:
```
4. 配置MySQL连接
```python
db_host = 'localhost' # 本地地址
db_port = tunnel.local_bind_port # 映射的端口
db_user = 'root' # MySQL用户名
db_password = 'xxxxxx' # MySQL密码
db_name = 'test' # 数据库名称
conn = pymysql.connect(
host=db_host,
port=db_port,
user=db_user,
password=db_password,
database=db_name,
charset='utf8mb4'
)
cursor = conn.cursor()
# 使用 cursor 进行数据库操作
# ...
cursor.close()
conn.close()
```
5. 完整代码示例
```python
import pymysql
from sshtunnel import SSHTunnelForwarder
ssh_host = 'xxx.xxx.xxx.xxx' # 云服务器的IP地址
ssh_port = 22 # 云服务器的SSH端口
ssh_user = 'root' # 云服务器的SSH用户名
ssh_password = 'xxxxxx' # 云服务器的SSH密码
with SSHTunnelForwarder(
(ssh_host, ssh_port), # 云服务器的SSH地址和端口
ssh_username=ssh_user,
ssh_password=ssh_password,
remote_bind_address=('localhost', 3306) # MySQL服务器的地址和端口
) as tunnel:
db_host = 'localhost' # 本地地址
db_port = tunnel.local_bind_port # 映射的端口
db_user = 'root' # MySQL用户名
db_password = 'xxxxxx' # MySQL密码
db_name = 'test' # 数据库名称
conn = pymysql.connect(
host=db_host,
port=db_port,
user=db_user,
password=db_password,
database=db_name,
charset='utf8mb4'
)
cursor = conn.cursor()
# 使用 cursor 进行数据库操作
# ...
cursor.close()
conn.close()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)