I’m trying to create dataBase in Postgre SQL Python, i got an error: CREATE DATABASE cannot run inside a transaction block. I have read that u need autocommit, but i already have it. What’s the problem
try:
with psycopg2.connect(
host=host,
user=rootUser,
password=rootPassword,
) as connection:
connection.autocommit = True
with connection.cursor() as cursor:
cursor.execute(
("CREATE DATABASE " + db_name + """ WITH
OWNER = """ + user + """ ENCODING = 'UTF8'
CONNECTION LIMIT = -1
IS_TEMPLATE = False;""")
)
2
Answers
First of all you have to ensure that you are using a psycopg version that supports autocommit, i.e version 2.73 or later. Also you have to set
autocommit
toTrue
before creating the cursor by modifying your code;Since v2.9,
with conn
starts a transaction (GitHub issue), so it can’t be used for actions like executingCREATE DATABASE
which must be issued outside a transaction.You can do it without using the context manager:
or like this