MySql教程

python3使用ssh隧道连接mysql

本文主要是介绍python3使用ssh隧道连接mysql,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

参考文章:https://blog.csdn.net/qq_33385691/article/details/105249507?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_default&utm_relevant_index=1

 

对原代码进行了整理

基本功能:填好SSH与MYSQL信息与SQL语句,直接以数组的形式出结果

 

 1 import pymysql
 2 from sshtunnel import SSHTunnelForwarder
 3 import pymysql.cursors
 4 
 5 def querySQL(ssh_config, db_config, sql):
 6     with SSHTunnelForwarder(
 7             (ssh_config['host'], ssh_config['port']),
 8             ssh_password = ssh_config['password'],
 9             ssh_username = ssh_config['username'],
10             remote_bind_address=(db_config['host'], db_config['port'])
11     ) as server:
12         db = pymysql.connect(
13             host = '127.0.0.1',
14             port = server.local_bind_port,
15             user = db_config['username'],
16             passwd = db_config['password'],
17             db = db_config['db_name'],
18             charset = "utf8",
19             cursorclass = pymysql.cursors.DictCursor)
20         cursor = db.cursor()
21         try:
22             cursor.execute(sql)
23             data = cursor.fetchall()
24             db.commit()
25         except:
26             db.rollback()
27 
28         collect = []
29         for result in data:
30             collect.append(result)
31         db.close()
32         cursor.close()
33         return collect
34 
35 if __name__ == "__main__":
36     # 远程登录配置信息
37     ssh_config = {
38         'host': '',
39         'port': 22,
40         'username': '',
41         'password': ''
42     }
43     # 数据库配置信息
44     db_config = {
45         'host': 'localhost',
46         'port': 3306,
47         'username': '',
48         'password': '',
49         'db_name': ''
50     }
51     # 查询语句
52     sql = 'show tables'
53     # 查询
54     result = querySQL(ssh_config, db_config, sql)
55     print (result)

 

这篇关于python3使用ssh隧道连接mysql的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!