0

I have the following constructor for my Dbconn class:

def __init__(self):
    self.host     = "localhost"
    self.database = "my_database"
    self.username = "username"
    self.password = "password"

    try:
        self.db = MySQLdb.connect(
            self.host,
            self.username,
            self.password,
            self.database
        )
        self.cursor = self.db.cursor()
    except:
        print "There was an error while connecting to the database"
        self.db.rollback()

however, when I execute the program, I get:

  File "database.py", line 39, in __init__
    self.db.rollback()
AttributeError: Dbconn instance has no attribute 'db'

Any clues why I'm getting that?

2
  • 1
    Only catch the exceptions that you know how to handle. In this case, I don't know what the problem is with your code, but it would be nice to know what the exception is that causes you to enter the except clause. Commented Feb 25, 2013 at 21:16
  • edit -- I do know what the problem is -- I just didn't look close enough. I still hold by my original statement -- Only handle exceptions that you expect and nothing more. Commented Feb 25, 2013 at 21:18

3 Answers 3

4

When MySQLdb.connect() fails, self.db is not set at all. There is no point in rolling back at that point.

Start by setting it to None, then test for that in the except handler:

db = None

def __init__(self):
    self.host     = "localhost"
    self.database = "my_database"
    self.username = "username"
    self.password = "password"

    try:
        self.db = MySQLdb.connect(
            self.host,
            self.username,
            self.password,
            self.database
        )
        self.cursor = self.db.cursor()
    except MySQLdb.Error:
        print "There was an error while connecting to the database"
        if self.db is not None:
            self.db.rollback()

I also made the exception handler more specific; blanket except handlers are rarely a good idea.

Sign up to request clarification or add additional context in comments.

Comments

1

Nothing gets assigned to self.db if MySQLdb.connect throws an exception.

Comments

0

If MySQLdb.connect fails, the db attribute won't be assigned. Also, what do you want to rollback if a connect to the DB failed?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.