views:

175

answers:

3

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

Need help urgent.

+2  A: 

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.

Douglas Leeder
+2  A: 

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.

kcwu
+1  A: 

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.

Alex Martelli
can u explain in more details
ha22109
Start by reading http://docs.python.org/library/multiprocessing.html which explains how to use the multiprocessing module in the standard library (2.6 or higher Python; if you're on 2.5, install the backport from code.google.com/p/python-multiprocessing/). Not much space in a comment to give many more details, but the idea is: make two Queues quin and quout, make a Process with the Queues, and when you need a SQL query push it on quin, the Process waits on that Queue, pulls the query, does it, pushes the results on quout; the requesting process kills the other if it's taking too long.
Alex Martelli