Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change database (postgresql) in python using psycopg2 dynamically

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()
like image 751
tailor_raj Avatar asked Dec 05 '12 09:12

tailor_raj


1 Answers

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()
like image 134
Michał Niklas Avatar answered Nov 03 '22 09:11

Michał Niklas