如何在python中获取Postgresql中的数据库列表

2024-09-28 01:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python列表获得Postgresql服务器中所有数据库的列表。 基本上,我想在另一个数据库中创建这些 但我没能拿到。在

这就是我试过的

config_read = {
          'host':'psql-002',
          'database':'tesdb',
          'user':'pguser',
          'port':'5432',
          'password':'mypass'
          }


class ExportPSQL():

    def __init__(self):
        try:
            conn = psycopg2.connect(**config_read) 
            self.conn = conn
        except:
            print "Eror Connecting database"  

    def run(self):
    # Get a list of databases with :
        db_command=" psql -h localhost -U pguser tesdb -c '\l'"
        db_list = os.popen(db_command)

Tags: selfconfig数据库列表readdbpostgresqldef
2条回答

解决方案中缺少的是读取和解析从psql获得的信息:

def get_database_info(host, user):
    records, _ = subprocess.Popen(['psql','-lA','-F\x02','-R\x01','-h',host,'-U',user ],stdout=subprocess.PIPE).communicate()
    records = records.split('\x01')
    header = records[1].split('\x02')
    return [dict(zip(header,line.split('\x02'))) for line in records[2:-1]]

以超级用户的身份使用^{}和{a2}完成所有操作

pg_dumpall -h localhost -U postgres -f pg_dumpall.sql

如果只想复制架构,那么使用 schema-only参数。在

将其还原到另一个群集

^{pr2}$

相关问题 更多 >

    热门问题