简单介绍
from sshtunnel import SSHTunnelForwarder
import os, pymysql
class MySqlSSH:
def __init__(self):
self.server = SSHTunnelForwarder(
ssh_address_or_host=('192.168.68.129', 22),
ssh_username='root',
ssh_password='xxxxxx',
remote_bind_address=('127.0.0.1', 3306)
)
self.server.start()
mysql_config = {
'user': 'root',
'passwd': 'xxxxxx',
'host': '127.0.0.1',
'port': self.server.local_bind_port,
'db': 'smartwatch'
}
self.mysql = pymysql.connect(**mysql_config)
self.cursor = self.mysql.cursor()
def fetch_one(self, sql):
self.cursor.execute(sql)
result = self.cursor.fetchone()
return result
def fetch_all(self, sql):
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result
def execute_sql(self, sql):
self.cursor.execute(sql)
self.mysql.commit()
result = "受影响的行数:{}".format(self.cursor.rowcount)
return result
def close(self):
self.cursor.close()
self.mysql.close()
self.server.close()
还可以另外封装方法方便调用
def conn_mysql(sql):
try:
conn = MySqlSSH()
if sql.split()[0].lower() == "select":
return conn.fetch_all(sql)
else:
return conn.execute_sql(sql)
except Exception as e:
GetLog.get_log().error(e)
raise
finally:
conn.close()