Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psycopg2: How to execute vacuum postgresql query in python script

I am using Python with psycopg2 and I'm trying to run a full VACUUM in python script. The problem is that when I try to run the VACUUM command within my code I get the following error:

psycopg2.InternalError: VACUUM cannot run inside a transaction block

The line which am trying to execute is:

sql="vacuum full table_name;"

cur.execute(sql)

How to resolve this error?

like image 376
Rohit Bhagat Avatar asked May 13 '15 05:05

Rohit Bhagat


People also ask

How do I run a vacuum in PostgreSQL?

Connect to the database and issue this command: "VACUUM". This causes a run in "lazy mode" that can be used during normal production use. It is recommended you actually invoke it as "vacuum analyze" which will also update statistics.

How do I run a SQL query in psycopg2?

SQL queries are executed with psycopg2 with the help of the execute() method. It is used to Execute a database operation query or command. Parameters can be provided in the form of a sequence or a mapping, and they'll be tied to variables in the operation.

What is psycopg2 used for in Python?

Python psycopg2 module APIs No. This API opens a connection to the PostgreSQL database. If database is opened successfully, it returns a connection object. This routine creates a cursor which will be used throughout of your database programming with Python.


1 Answers

Psycopg2 starts a new transaction for each call to .execute().

Open an autocommit connection to handle a vacuum.

http://initd.org/psycopg/docs/connection.html#connection.autocommit

like image 138
Ron Dunn Avatar answered Oct 15 '22 00:10

Ron Dunn