Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error messages from psycopg2 exceptions

Tags:

This is my first project using psycopg2 extensively. I'm trying to find a way to extract the psql error message for whenever a connection attempt fails. I've tested the code below will work if all the variables are set correctly, however whenever an error condition occurs (e.g. user chooses a database that doesn't exist), Python will give me the following:

I am unable to connect to the database None Traceback (most recent call last):   File "./duplicate_finder.py", line 163, in <module>     main(sys.argv[1:])   File "./duplicate_finder.py", line 142, in main     print e.diag.message_detail AttributeError: 'OperationalError' object has no attribute 'diag' 

Is there a simple, catch-all method to catch whatever error message psql generates when a connection fails, or do I need to write except blocks for multiple psycopg2 exceptions?

Extract from my script:

import sys, getopt, os, time, csv, psycopg2      ...     ...      conn_string = "host=" + dbhost + " dbname=" + database + " user=" + dbuser + " password=" + dbpass     try:         conn = psycopg2.connect(conn_string)     except psycopg2.Error as e:         print "Unable to connect!"         print e.pgerror         print e.diag.message_detail         sys.exit(1)     else:         print "Connected!"         cur = conn.cursor()         cur.execute("SELECT id, lastname, firstname, location FROM test ORDER BY ctl_upd_dttm DESC;")         print cur.fetchone()         ...         conn.close() 
like image 665
sirjames2004 Avatar asked Jun 20 '14 16:06

sirjames2004


People also ask

Does psycopg2 work with Python 3?

The current psycopg2 implementation supports: Python versions from 3.6 to 3.10. PostgreSQL server versions from 7.4 to 15. PostgreSQL client library version from 9.1.

Is psycopg2 connection thread safe?

Thread and process safetyThe Psycopg module and the connection objects are thread-safe: many threads can access the same database either using separate sessions and creating a connection per thread or using the same connection and creating separate cursors. In DB API 2.0 parlance, Psycopg is level 2 thread safe.

Is psycopg2 asynchronous?

Psycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY. Please refer to the PostgreSQL documentation for examples about how to use this form of communication.

Is psycopg2 a database driver?

Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for multi-threaded applications and manages its own connection pool.


2 Answers

When I try to catch exceptions, e.pgerror is always None for connection errors. The following code block gets around this by directly printing 'e'.

try:     conn = psycopg2.connect(conn_string) except psycopg2.OperationalError as e:     print('Unable to connect!\n{0}').format(e)     sys.exit(1) else:    print('Connected!')    # do stuff 

For example, in the case of password authentication failure:

Unable to connect! FATAL:  password authentication failed for user "user" 

I realize this question is a year old but hopefully might help someone in the future

like image 90
sdemurjian Avatar answered Nov 08 '22 18:11

sdemurjian


Ended up here because of

class 'psycopg2.errors.InvalidCursorName'

on Django. If that's your case, be sure to makemigrations

like image 42
Alvaro Rodriguez Scelza Avatar answered Nov 08 '22 19:11

Alvaro Rodriguez Scelza