Cancel query execution in pyscopg2

How can I cancel a query using pyscopg2 (python Postgres driver)?

As an example, suppose I have the following code:

import psycopg2 cnx_string = "something_appropriate" conn = psycopg2.connect(cnx_string) cur = conn.cursor() cur.execute("long_running_query") 

Then I want to cancel execution of this long request from another thread - what method do I need to call for connection / cursor objects for this?

+4
source share
2 answers

You can cancel the query by calling the pg_cancel_backend(pid) PostgreSQL function in a separate connection.

You can find out the PID backend for cancellation from the connection.get_backend_pid() method psycopg2 (available from version 2.0.8).

+4
source

psycopg2 support for asynchronous execution has been removed .

If you can use py-postgresql and transactions (it py3k), the internal implementation is asynchronous and supports interruption.

0
source

All Articles