Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgres pg8000 create database

I am trying to create a database with pg8000 driver of postgressql , but unable to create. Creating a db manually and then connecting to it works fine with me, but i need to create db with my code. I am getting error "sqlalchemy.exc.ProgrammingError: (pg8000.ProgrammingError)". I have tried below code for creating a db.

from sqlalchemy import create_engine
dburl = "postgresql+pg8000://user:pswd@myip:5432/postgres/"
engine = create_engine(dburl)
conn = engine.connect()
conn.execute("COMMIT")
conn.execute("CREATE DATABASE qux")

I also tried with below -

from sqlalchemy import create_engine
from sqlalchemy.engine import url
settings ={"drivername" : "postgresql+pg8000", "host" : "myip","port" : 5432,"username" : "user","password" : "pswd","database" : "MyTestDB"}
db=create_engine(url.URL(**settings))
db.execute("commit")

This is the exact Error i am getting """sqlalchemy.exc.ProgrammingError: (pg8000.ProgrammingError) ('ERROR', '25001', 'CREATE DATABASE cannot run inside a transaction block') [SQL: 'create database workDB']""""

Please suggest as to how i can create this db...

like image 515
tec_abhi Avatar asked Sep 27 '26 02:09

tec_abhi


1 Answers

Here's a solution:

from sqlalchemy import create_engine
dburl = "postgresql+pg8000://user:pswd@myip:5432/postgres/"
engine = create_engine(dburl)
conn = engine.connect()

con.rollback()  # Make sure we're not in a transaction
con.autocommit = True  # Turn on autocommit

conn.execute("CREATE DATABASE qux")
 
con.autocommit = False  # Turn autocommit back off again

The docs talk about this problem of executing commands that can't be run in a transaction. The thing is that pg8000 automatically executes a begin transaction before any execute() if there isn't already a transaction in progress. This is fine until you come to execute a command that can't be executed inside a transaction. In that case you have to enter autocommit mode, which implicitly starts a transaction before the statement and commits it afterwards, but automatically avoids doing this if (like CREATE DATABASE) the statement can't be executed within a transaction.

like image 54
Tony Locke Avatar answered Sep 29 '26 15:09

Tony Locke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!