0

I have been trying to write a script to test if connection to a certain mysql DB is possible.

If it is possible it should give a "OK" Output and if not It is suppose to say "FAIL" and carry on with operation.

It works fine when connection is available. But when the connection fails to connect the script gets exited giving an error

_mysql_exceptions.OperationalError: (1045, "Access denied for user 'yoda'@'localhost' (using password: YES)")

But this interferes from script doing rest of the process

I called it like

if not db.connect(UnivConf['DBHT'],UnivConf['DBUN'],UnivConf['DBPW'],UnivConf['DBDB'])

How can I solve this problem and get the script to continue on without quitting

3
  • 4
    Why don't you put it inside a try ... except block? Commented Feb 23, 2013 at 18:02
  • 1
    why should the script continue? if you don't have a valid DB connection, then any other db code later on is going to fail anyways. basically "my car just exploded. how can I keep driving down the highway anyways?" Commented Feb 23, 2013 at 18:02
  • I need to log database server status at regular times, Commented Feb 23, 2013 at 18:09

1 Answer 1

4

Try try

try:
    if not db.connect(UnivConf['DBHT'],UnivConf['DBUN'],UnivConf['DBPW'],UnivConf['DBDB'])
        # Do something

except _mysql_exceptions.OperationalError as e:
    print "Caught an exception : " + str(e.message)
    print "Something blah blah..."

finally:
    print "Done"
Sign up to request clarification or add additional context in comments.

4 Comments

For completeness, I would add else:
@JakubM. for completeness of your comment, what would you put in the else (I actually want to know :o)
The answer for the OP question is a basic Python concept, so for educational purposes, I would add a full try/except/else/finally example. But probably this comment is educational enough :)
You can remove the 'if' completely. The try/except catches db connection failures. Its not right in any case, because it does not save the connection object which you need to do anything useful.

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.