简体   繁体   English

使用psycopg2动态更改python中的数据库(postgresql)

[英]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... 任何人都可以告诉我如何动态更改我刚刚创建的数据库..使用以下代码...我认为在执行此代码期间我将在默认的postgres数据库(这是模板数据库)和新数据库之后创建我想在运行时更改我的数据库以进行进一步处理...

    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. 您只需使用database=dbname参数再次连接即可。 Note usage of SELECT current_database() to show on which database we work, and SELECT * FROM pg_database to show available databases: 注意使用SELECT current_database()来显示我们工作的数据库,并使用SELECT * FROM pg_database来显示可用的数据库:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM