Getting error condition from MySQLdb

D

Derek Fountain

I was trying to use MySQLdb to connect to a database. All is OK, except I
can't figure out how to get the details of an error. Suppose I try to
connect to a non existant server, or with the wrong password - how do I get
a meaningful error message which I can present to my user?
 
A

Andy Todd

Derek said:
I was trying to use MySQLdb to connect to a database. All is OK, except I
can't figure out how to get the details of an error. Suppose I try to
connect to a non existant server, or with the wrong password - how do I get
a meaningful error message which I can present to my user?

In Python whenever an error occurs an exception is raised. I'd suggest a
quick read of the section of the tutorial that explains this;

http://www.python.org/doc/current/tut/node10.html

Then fire up a Python command prompt and try some things out. For
instance, on my Windows machine if I try;

I get a nice traceback;

Traceback (most recent call last):
File "<input>", line 1, in ?
File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\__init__.py",
line 63, in Connect
return apply(Connection, args, kwargs)
File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\connections.py",
line 115, in __init__
self._make_connection(args, kwargs2)
File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\connections.py",
line 41, in _make_connection
apply(super(ConnectionBase, self).__init__, args, kwargs)
OperationalError: (2003, "Can't connect to MySQL server on 'localhost'
(10061)")

If I actually start up MySQL, I get;

Traceback (most recent call last):
File "<input>", line 1, in ?
File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\__init__.py",
line 63, in Connect
return apply(Connection, args, kwargs)
File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\connections.py",
line 115, in __init__
self._make_connection(args, kwargs2)
File "C:\PROGRA~2\PYTHON23\Lib\site-packages\MySQLdb\connections.py",
line 41, in _make_connection
apply(super(ConnectionBase, self).__init__, args, kwargs)
OperationalError: (1049, "Unknown database 'wibble'")

Note that MySQLdb, like the majority of distributed modules, defines its
own exceptions. MySQLdb, to the best of my knowledge, implements the
standard DB-API exceptions. They are detailed here;

http://www.python.org/topics/database/DatabaseAPI-2.0.html

Regards,
Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top