Python3 MySQL正常连接与ssh跳板连接


一、所需Python库

1.mysql.connector(pip install mysql.connector)
2.pymysql(pip install pymysql)
3.sshtunnel(pip install sshtunnel)

二、连接方式

1.正常连接(mysql允许远程访问)

import mysql.connector

db = mysql.connector.connect(
        host = "192.168.1.1",     # ip
        port = 3306,              # 数据库端口
        user = "test",            # 数据库用户名
        passwd = "test",          # 数据库密码
        database = "test"         # 需连接数据库名
        auth_plugin = "mysql_native_password"  # mysql8需添加
    ) 
    
mycursor = db.cursor() # 新建游标
mycursor.execute(sql)  # 执行sql语句
    
print("mycursor.fetchone()")  # sql查询输出方式一条,str
print("mycursor.fetchmany(4)")  # sql查询输出方式多条,参数为数量,list
print("mycursor.fetchall()")  # sql查询输出方式所有,list
    
db.commit()   # sql修改提交保存
print(mycursor.rowcount, "条记录修改")  # 发生修改数量

mycursor.close()  # 游标关闭
db.close()  # 数据库关闭,用完记得关闭,免得浪费资源,怕忘记关闭使用with语句也可以

2.ssh跳板连接(适用云数据库内网ip)

import pymysql
from sshtunnel import SSHTunnelForwarder

with SSHTunnelForwarder(
        ('114.114.114.114', 22),    # 跳板服务器ip,ssh端口
        ssh_username="test",    # 跳板ssh用户名
        ssh_password="test",    # 跳板ssh密码
        # ssh_pkey=r"F:\test\test.pem",  # 跳板数据库密钥
        remote_bind_address=('10.0.0.1', 3306)) as server:  # 数据库ip,端口
    db = pymysql.connect(
        host='127.0.0.1',   # 默认即可
        port=server.local_bind_port,
        user='test',   # 数据库用户名
        passwd='test', # 数据库密码
        db='test')     # 需连接数据库名
        
	mycursor = db.cursor() # 新建游标
	mycursor.execute(sql)  # 执行sql语句
    
	print("mycursor.fetchone()")  # sql查询输出方式一条,str
	print("mycursor.fetchmany(4)")  # sql查询输出方式多条,参数为数量,list
	print("mycursor.fetchall()")  # sql查询输出方式所有,list
    
	db.commit()   # sql修改提交保存
	print(mycursor.rowcount, "条记录修改")  # 发生修改数量
	
	db.close()  # 数据库连接关闭,不关闭无法退出
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值