Can anybody tell me how can I change database dynamically which I have created just now.. using the following code... I think during the execution of this code I will be in default postgres database (which is template database) and after new database creation I want to change my database at runtime to do further processing...
from psycopg2 import connect
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
dbname = 'db_name'
con = connect(user ='postgres', host = 'localhost', password = '*****')
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
cur.execute('CREATE DATABASE ' + dbname)
cur.close()
con.close()
You can simply connect again with
database=dbname
argument. Note usage ofSELECT current_database()
to show on which database we work, andSELECT * FROM pg_database
to show available databases: