在通过ssh 方法连接数据库时需要注意两层连接问题.
ssh 连接通道连接服务器
mysql 连接会话连接数据库
在python 中关闭服务器连接前,需要关闭数据库连接.否则出现线程锁死(不能关闭服务器连接)
以下为代码实例.
from sshtunnel import SSHTunnelForwarder
from sqlalchemy import create_engine
import pymysql
import pandas as pd
from sqlalchemy.pool import NullPool
server = SSHTunnelForwarder(
('******', 22),
ssh_username="***",
ssh_pkey='***',
remote_bind_address=('127.0.0.1', 3306))
server.start()
engine = create_engine(
'mysql+pymysql://user:password*@127.0.0.1:%s/db?charset=utf8' % server.local_bind_port,poolclass=NullPool)
pd_dataFrame = pd.read_sql('target_feature', engine)
print(pd_dataFrame)
# 以下注释部分为pymysql方式连接
# myConfig = pymysql.connect(
# user="****",
# passwd="****",
# host="127.0.0.1", # 此处必须是 127.0.0.1
# db='***',
# port=server.local_bind_port)
# cursor = myConfig.cursor()
# cursor.execute('SELECT * FROM target_feature;')
# print(cursor.fetchall())
# myConfig.close()
server.stop()