1、通过pip安装pymysql和sshtunnel
注意要在安装目录python\script下面执行
2、脚本输出
from sshtunnel import SSHTunnelForwarder
import pymysql
##创建数据库连接,不需要打开和关闭
with SSHTunnelForwarder(
##跳板机配置
('XXX.XXX.XXX.XXX',22),
ssh_password="XXX",
ssh_username="XXX",
##数据库配置
remote_bind_address=('XXX.XXX.XXX.XXX',3306)) as server:
conn=pymysql.connect(
host='127.0.0.1',
port=server.local_bind_port,
user='XXX',
password='XXX',
db='XXX',
charset='utf8')
##print(conn) #连接成功会返回:pymysql.connections.Connection object at 0x00000290B2915FD0
##创建操作的游标
cursor=conn.cursor()
##设置输入输出的编码格式和自动提交
cursor.execute('set names utf8')
cursor.execute('set autocommit = 1')#0:false 1:trueS
##编写SQL语句
sql="select * from sl_activity_common where id='65';"
print(sql)
##执行SQL
cursor.execute(sql)
##得到结果集
#result=cursor.fetchall()#得到全部
#result1=cursor.fetchone()
result2=cursor.fetchmany(1)
print(result2)
#关闭游标
cursor.close()
3、如果没有跳板机可直接连接
conn = connect(host='sqlhost', port=3306, db='python_test_1', user='root', password='mysql', charset='utf8')
注意需要关闭连接