我的目标是创建一个对象(DBSession
)来处理与数据库的连接,而不是直接与MySQLdb
和sshtunnel
模块进行交互。但是,当我运行此代码时,DBSession
对象实例化之后的紧随其后的行永远不会运行。
import MySQLdb as db
import pandas as pd
from sshtunnel import SSHTunnelForwarder
class DBSession:
def __init__(self, sshcreds, dbcreds):
self.sshcreds = sshcreds
self.dbcreds = dbcreds
with SSHTunnelForwarder(
#ssh setup stuff
) as server:
self.connection = db.connect(
#db setup stuff
)
session = DBSession(sshcreds, dbcreds)
df = pd.read_sql_query( # <-- this line is never executed
"select * from users limit 1",
session.connection
)
session.connection.close()
我在MySQL Workbench上使用了show processlist
,并且可以肯定的是,该连接显示为活动状态,但是没有任何实际代码发送给该连接:
我的直觉告诉我,这与将查询代码分配给查询连接的不同时刻有关。就像连接已经建立一样,所以我无法追溯地为其分配代码。
我正在努力寻找正确的设计模式,该模式将允许我在逻辑中使用DBSession
对象,而不必在对象中放入逻辑并容纳:S。 MySQLdb不是为我打算做什么设计的吗?