ha22109
ha22109

Reputation: 8316

db connection in python

I am writing a code in python in which I established a connection with database. I have queries in a loop. While queries being executed in the loop , If i unplug the network cable it should stop with an exception. But this not happens, When i again plug yhe network cabe after 2 minutes it starts again from where it ended. I am using linux and psycopg2. It is not showing exception

Upvotes: 0

Views: 511

Answers (3)

Alex Martelli
Alex Martelli

Reputation: 881497

If you want to implement timeouts that work no matter how the client library is connecting to the server, it's best to attempt the DB operations in a separate thread, or, better, a separate process, which a "monitor" thread/process can kill if needed; see the multiprocessing module in Python 2.6 standard library (there's a backported version for 2.5 if you need that). A process is better because when it's killed the operating system will take care of deallocating and cleaning up resources, while killing a thread is always a pretty unsafe and messy business.

Upvotes: 1

kcwu
kcwu

Reputation: 7011

As Douglas's answer said, it won't raise exception due to TCP.

You may try to use socket.setdefaulttimeout() to set a shorter timeout value.

setdefaulttimeout(...)

   setdefaulttimeout(timeout)

   Set the default timeout in floating seconds for new socket objects.
   A value of None indicates that new socket objects have no timeout.
   When the socket module is first imported, the default is None.

However, it may not work if your database connection is not build by python socket, for example, native socket.

Upvotes: 2

Douglas Leeder
Douglas Leeder

Reputation: 53310

Your database connection will almost certainly be based on a TCP socket. TCP sockets will hang around for a long time retrying before failing and (in python) raising an exception. Not to mention and retries/automatic reconnection attempts in the database layer.

Upvotes: 2

Related Questions