Getting error condition from MySQLdb

Andy Todd andy47 at halfcooked.com
Mon Nov 3 05:59:27 EST 2003


Derek Fountain wrote:

> 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;

 >>> import MySQLdb
 >>> mydb=MySQLdb.connect(db='wibble')

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
-- 
--------------------------------------------------------------------------------
 From the desk of Andrew J Todd esq - http://www.halfcooked.com/







More information about the Python-list mailing list