我有一个定义MySQL连接的类。问题是我无法使用该类的实例,因为MySQL连接似乎已经关闭。
这是我的课程:
import mysql.connector
import sshtunnel
class DB:
def __init__(self):
self.pem = '...'
self.config = {
...
}
sshtunnel.SSH_TIMEOUT = 10.0
sshtunnel.TUNNEL_TIMEOUT = 10.0
with sshtunnel.SSHTunnelForwarder(
ssh_address = ('xx', yy),
ssh_username = 'test123',
ssh_pkey = self.pem,
remote_bind_address = ('test.com', 3306)
) as tunnel:
self.db = mysql.connector.MySQLConnection(**self.config, port = tunnel.local_bind_port)
def connection(self):
return self.db
使用
创建实例后db = DB()
conn = db.connection()
我正在尝试执行以下代码:
cursor = conn.cursor()
query = ("""
SELECT *
FROM user
WHERE user_id = 1
""")
cursor.execute(query)
rows = cursor.fetchall()
print(rows)
我收到以下消息:
MySQL连接不可用。