David542
David542

Reputation: 110267

Python re-connecting to MySQLdb

I have the following:

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

This is what it looks like when I try and reconnect:

>>> 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>

Why won't it allow me to re-open the connection? How would I re-open it, or do I need to create a new instance?

Upvotes: 0

Views: 277

Answers (2)

whuiscool
whuiscool

Reputation: 75

The function "close_conn" return self_conn after it colseed connection. So the virable self_conn always be true, right?

Upvotes: 0

jimw
jimw

Reputation: 2598

You're testing whether self.conn is 'None' but it's not - it's still a mysql connection object. One of its properties or methods will tell you whether it's open or not, so you could test that instead, or set self.conn to None in close_conn if that's easier.

Upvotes: 2

Related Questions