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?
You haven’t defined
self.connanywhere. You’re only settingconnas a local inside ofget_conn. Defineself.connin your constructor, and then updateget_connto setself.conn. Like this:Also, check whether
self.connis set first as opposed to creating a new one each time inget_conn, like this:Finally, call the
get_connmethod like this: