Writing an object-oriented MySQLdb connection

python

Solution

You haven't defined `self.conn` anywhere. You're only setting `conn` as a local inside of `get_conn`. Define `self.conn` in your constructor, and then update `get_conn` to set `self.conn`. Like this:

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

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

Also, check whether `self.conn` is set first as opposed to creating a new one each time in `get_conn`, like this:

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

Finally, call the `get_conn` method like this:

mydbconnobj = DBConnection('localhost',3306,'foouser','foopass','foodbname')
mydbconn = mydbconnobj.get_conn()

Problem

I am trying to learn OOP, and I am using the database connection via `MySQLdb` as my first test. This is what I have so far: ``` 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 def get_conn(self): conn = MySQLdb.connect (host = self.DB_HOST, port = self.DB_PORT, db = DB_NAME, user = DB_USER, passwd = DB_PASSWORD) return conn def get_cursor(self): cursor = self.conn.cursor() return cursor def get_dict_cursor(self): dict_cursor = self.conn.cursor(MySQLdb.cursors.DictCursor) return dict_cursor ``` Is the above valid? Does `self.conn` refer to `get_conn()` or is this an invalid reference. How would I establish a connection to the database and then get a cursor, using the python shell?

Original source