3

I want to get the list of all databases in Postgresql server in python list. Basically then i want to create those insode another database But i am not able to get it.

This is what i have tried

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)
5
  • 3
    Take a look at dba.stackexchange.com/a/1304 . Commented Jun 22, 2014 at 7:01
  • Which is the other database? Postgresql? Commented Jun 22, 2014 at 7:33
  • @ClodoaldoNeto yes other databse is also postgres Commented Jun 22, 2014 at 7:37
  • So why don't you do it all in Postgresql in instead of using Python? Commented Jun 22, 2014 at 7:52
  • @ClodoaldoNeto how can i do it in postgres. i thought i had to manually export and import each database and i had 30 databases. so i thought i will automate it with python Commented Jun 22, 2014 at 12:03

2 Answers 2

2

Do it all with pg_dumpall and psql as superuser

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

If you want to copy only the schema then use the --schema-only parameter.

To restore it to another cluster

psql -f pg_dumpall.sql postgres
Sign up to request clarification or add additional context in comments.

Comments

2

What's missing in your solution is the reading and parsing of the information you get from 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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.