12

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()
1
  • 3
    You can't change databases in PostgreSQL without making a new connection, so Michal is quite right. Commented Dec 5, 2012 at 12:17

1 Answer 1

19

You can simply connect again with database=dbname argument. Note usage of SELECT current_database() to show on which database we work, and SELECT * FROM pg_database to show available databases:

from psycopg2 import connect
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT

def show_query(title, qry):
    print('%s' % (title))
    cur.execute(qry)
    for row in cur.fetchall():
        print(row)
    print('')

dbname = 'db_name'
print('connecting to default database ...')
con = connect(user ='postgres', host = 'localhost', password = '*****', port=5492)
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
show_query('current database', 'SELECT current_database()')
cur.execute('CREATE DATABASE ' + dbname)
show_query('available databases', 'SELECT * FROM pg_database')
cur.close()
con.close()

print('connecting to %s ...' % (dbname))
con = connect(user ='postgres', database=dbname, host = 'localhost', password = '*****', port=5492)
cur = con.cursor()
show_query('current database', 'SELECT current_database()')
cur.close()
con.close()
1
  • 2
    Is there no way to update the connection's database binding without closing it and reconnecting? Commented Jul 18, 2023 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.