Python重新连接到MySQLdb

时间:2012-04-16 22:59:43

标签: python mysql

我有以下内容:

class DBConnection:
    def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME):
        self.host = DB_HOST
        self.port = DB_PORT
        self.name = DB_NAME
        self.user = DB_USER
        self.password = DB_PASSWORD
        self.conn = None
        self.cursor = None

    def get_conn(self):
        if self.conn is None:
            self.conn = MySQLdb.connect (host = self.host, port = self.port, db = self.name, user = self.user, passwd = self.password)
        return self.conn

    def close_conn(self):
        if self.conn:
            self.conn.close()
        return self.conn

这是我尝试重新连接时的样子:

>>> from db_conn import DBConnection
>>> db = DBConnection(DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME)
>>> db.get_conn()
<_mysql.connection open to '127.0.0.1' at 7fbb1b8a2420>
>>> db.close_conn()
>>> db.conn
<_mysql.connection closed at 7fbb1b8a2420>
>>> db.get_conn()
<_mysql.connection closed at 7fbb1b8a2420>

为什么不允许我重新打开连接?我该如何重新打开它,还是需要创建一个新实例?

2 个答案:

答案 0 :(得分:2)

你正在测试self.conn是否为'None'但它不是 - 它仍然是一个mysql连接对象。它的一个属性或方法会告诉你它是否打开,所以你可以测试它,或者如果更容易的话,在close_conn中将self.conn设置为None。

答案 1 :(得分:0)

函数“close_conn”在关闭连接后返回self _conn。所以变量self _conn总是正确的,对吗?