使用psycopg2动态更改python中的数据库(postgresql) [英] change database (postgresql) in python using psycopg2 dynamically

查看:296
本文介绍了使用psycopg2动态更改python中的数据库(postgresql)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何动态更改刚刚创建的数据库吗?。使用以下代码...
我认为在执行此代码期间,我将位于默认的postgres数据库中(模板数据库),并在创建新数据库后,我想在运行时更改数据库以进行进一步处理...

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()


推荐答案

使用 database = dbname 参数再次连接。请注意使用 SELECT current_database()来显示我们在哪个数据库上工作,以及 SELECT * FROM pg_database 来显示可用数据库:

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()

这篇关于使用psycopg2动态更改python中的数据库(postgresql)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆