Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel a postgres query in java/JDBC

How do I cancel a long running postgres query via JDBC or Java?

The usecase would be that an user starts a query on a postgres database via a front end, but then he decides otherwise and wants to abort/cancel the currently running query.

like image 215
Dieter Avatar asked Oct 06 '09 15:10

Dieter


People also ask

How do I cancel a postgresql query?

In an interactive psql session, you can simply hit Ctrl+C to send a cancel request, and GUI clients usually have a button for that purpose. But it is also possible to cancel somebody else's query by calling the database function pg_cancel_backend() .

How do you kill a running process in postgresql?

If you want to terminate all running queries, the following statement can be executed: SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE state = 'active' and pid <> pg_backend_pid(); The above statement will kill all active queries and should only be used in special situations.

How do you stop a query execution in Pgadmin?

According to the docs, pg_cancel_backend will stop the current query in that process, but pg_terminate_backend will finish the session in that proceses. A connected app can recover from a failed query, but to recover from a closed session it would need to open a new cursor.


1 Answers

Call java.sql.PreparedStatement.cancel() method. Check whether postgres JDBC driver supports this method. As far as I can see from the source code of the latest postgres JDBC driver it does stop the query.

like image 61
Boris Pavlović Avatar answered Sep 28 '22 16:09

Boris Pavlović