pyPgSQL DatabaseError details

Gerhard Haering gerhard.haering at gmx.de
Sun Dec 29 15:09:55 EST 2002


* Reid Lai <reidlai at reidlai.com> [2002-12-30 00:22 +0800]:
> Hi There,
> 
> I am newbie using Python and write a program which connects with my 
> PostgreSQL 7.2.x database.  In this program, I use try ... except 
> PySQL.DatabaseError ... statement to display error in shell level.  It 
> works fine.  But now I am thinking to enhance error message and 
> encountered a problem.
> 
> How can I extract information from DatabaseError exception to determine 
> if database connection problem is due to availability of database 
> service or incorrect user id and password?  Thanks for any help.

Unfortunately, PostgreSQL doesn't have the concept of error numbers, so you'd
have to interpret the error message yourself. pyPgSQL does most of the work for
you in that it returns the error 'notices' if you convert the exception to a
string.

This piece of code might be a start:

#v+
from pyPgSQL import PgSQL

try:
    con = PgSQL.connect(...)
except PgSQL.DatabaseError, exc:
    message = str(exc)
    if message.startswith("could not connect to server"):
        print "server not available"
    elif message.find("Password authentication failed") >= 0:
        print "wrong username or password"
    else:
        print "other error:"
        print message
#v-

This situation is suboptimal, to say the least. Especially because these error
messages might change in the future, or be in other languages for localized
versions of PostgreSQL :-( We really need error numbers.

I believe the safest solution is to just display str(exc) to the user and let
the user interpret it (if the password was wrong or if the administrator needs
to be alerted because network or database is down).

HTH,

Gerhard
-- 
Favourite database:             http://www.postgresql.org/
Favourite programming language: http://www.python.org/
Combine the two:                http://pypgsql.sf.net/
Embedded database for Python:   http://pysqlite.sf.net/




More information about the Python-list mailing list