How to resolve PostgreSQL Error: psycopg2.errors.ActiveSqlTransaction: CREATE DATABASE cannot run inside a transaction block | Python | Using PostgreSQL with Python
Solution:
Step 1: Set the isolation level for the PostgreSQL transaction using psycopg2
The psycopg2 adapter will raise an ActiveSqlTransaction exception if you don’t set the connection object’s set_isolation_level attribute. This is because the CREATE DATABASE statement won’t work unless AUTOCOMMIT is set to ON.
from psycopg2 import connect, extensions
host = "localhost"
user = "postgres"
password = "your password"
connection = connect(host=host, user=user, password=password, port="5432")
get the isolation leve for autocommit
autocommit = extensions.ISOLATION_LEVEL_AUTOCOMMIT
print ("ISOLATION_LEVEL_AUTOCOMMIT:", extensions.ISOLATION_LEVEL_AUTOCOMMIT)
set the isolation level for the connection's cursors
will raise ActiveSqlTransaction exception otherwise
conn.set_isolation_level( autocommit )
cur = connection.cursor()
query = "CREATE DATABASE YOUR_DB_NAME"
cur.execute(query)
connection.close()
On this page of the site you can watch the video online PostgreSQL| psycopg2.errors.ActiveSqlTransaction: CREATE DATABASE cannot run inside a transaction with a duration of hours minute second in good quality, which was uploaded by the user Development With Sachin 26 November 2022, share the link with friends and acquaintances, this video has already been watched 3,091 times on youtube and it was liked by 14 viewers. Enjoy your viewing!