一、所需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() # 数据库连接关闭,不关闭无法退出