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

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

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

您可以简单地再次与

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

from psycopg2 import connectfrom psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMITdef 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()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5640042.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存