I am using psycopg2 to access my postgres database in python. My function is to create a new database, the code is as follows:
def createDB(host, username, dbname):
adminuser = settings.DB_ADMIN_USER
adminpass = settings.DB_ADMIN_PASS
try:
conn=psycopg2.connect(user=adminuser, password=adminpass, host=host)
cur = conn.cursor()
cur.execute("CREATE DATABASE %s OWNER %s" % (nospecial(dbname), nospecial(username)))
conn.commit()
except Exception, e:
raise e
finally:
cur.close()
conn.close()
def nospecial(s):
pattern = re.compile('[^a-zA-Z0-9_]+')
return pattern.sub('', s)
When I call createDB, my postgres server throws an error: CREATE DATABASE cannot work inside a transaction block with error code 25001, which means "ACTIVE SQL TRANSACTION".
I am sure that at the same time there is no other connection, and every connection that I used before calling createDB is disconnected.
source
share