尝试使用MySQL Connection实例时将其关闭

时间:2019-05-10 10:58:59

标签: python mysql ssh

我有一个定义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连接不可用。

0 个答案:

没有答案