Ok, so I'm really new to python, especially the OO exception handling flow of things. I'm writing a class that will be handling MySQLdb calls, as a wrapper. The MySQLdb part of it makes enough sense, but I'm not quite sure how to go about handling connection errors and the like.
My thoughts are:
* The scripts using the class simply make a call to a method that retrieves data from the MySQL DB.
* The method determines if the DB is connected, and takes appropriate action to connect, if not.
* Connection errors (exceptions) should prolly be passed up through the chain of methods so that the calling script can deal with the exception
I don't know if my logic is good or not, quite frankly, because OO is still quite new to me. Can someone take a look at the example I've given and see if I'm going in the right direction, and if not, offer suggestions for logic improvements?
Code:
#!/usr/bin/env python
import sys
class Base:
def __init__(self):
self.sqldatabase = 'project_v11'
self.sqlname = 'chuck'
self.sqlpassword = 'merriweather'
self.db = None
def jobSearch(self, searchFor=''):
try:
if self.db is None:
self.sqlConnect()
print 'connect ok'
except Exception, e:
raise Exception, e
def sqlConnect(self):
try:
import MySQLdb
self.db = MySQLdb.connect(
host = 'localhost',
user = self.sqlname,
passwd = self.sqlpassword,
db = self.sqldatabase)
except Exception, e:
raise Exception, e
def sqlDone(self):
try:
self.db.close()
except Exception, e:
raise Exception, e
if __name__=='__main__':
try:
base = Base()
base.jobSearch(searchFor='test')
base.sqlDone()
except Exception, e:
print e
As of this moment, the database "project_v11" does not exist, so when I run the script, it errors out as:
Code:
/usr/lib/python2.3/ccae> ./Base.py
(1049, "Unknown database 'project_v11'")
And that is expected. However, I'm handling the Exceptions are generic, and I assume that this is bad practice. I'm just not sure what way is "correct".
Thanks!!!!
TLD