I have a huge problem:
There seems to be some hardware problems on the router of the server my python software runs on. The connection to the database only is successfull about every third time. So a psycopg2.connect() can take up to 5 minutes before I get an timeout exception.

2014-12-23 15:03:12,461 - ERROR - could not connect to server: Connection timed out
    Is the server running on host "" and accepting

That’s the code I’m using.

# Connection to the DB
    db = psycopg2.connect(host=dhost, database=ddatabase,
                          user=duser, password=dpassword)
    cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor)

except psycopg2.DatabaseError, err:
    logging.info('program terminated')

I tried some timeout additions for the query, but that didn’t helped, since the connection didn’t got established at all.

Is there a way, I can stop the program immediately, when the connection couldn’t be established?

When using the keyword arguments syntax to the connect function it is possible to use any of the libpd supported connection parameters. Among those there is connect_timeout in seconds:

db = psycopg2.connect (
    host=dhost, database=ddatabase,
    user=duser, password=dpassword,



A connection time out raises an OperationalError exception.