Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel query execution in pyscopg2

How would one go about cancelling execution of a query statement using pyscopg2 (the python Postgres driver)?

As an example, let's say 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 the execution of that long running query from another thread - what method would I have to call on the connection/cursor objects to do this?

like image 408
jwoolard Avatar asked Jan 11 '10 13:01

jwoolard


1 Answers

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

You can know the PID of the backend to cancel from the connection.get_backend_pid() method of psycopg2 (available from version 2.0.8).

like image 117
piro Avatar answered Sep 30 '22 04:09

piro