简体   繁体   中英

Generate postgresql database backup using python

I'm newbie to python and sql.

  1. I want to list all tables in database using python script
  2. I want to get create sql query for existing postgresql table using python

Could anyone please suggest a solution? 🙏🙏🙏

Your needs are not very clear, give more information about your environment. And why use python you don't really need it. You can use pg_dump tool and set timer or evenement with bash script ?

pg_dump dbname > dbname.bak

You can recover your old database .bak :

psql dbname < dbname.bak

No sql required.

If you really need to do it with python and SQL queries, use psycopg2 library for establish connection and execute some SQL queries:

import psycopg2
import psycopg2.extras
def pgsql_connect():
# Try to connect to an existing postgresql database
db = getattr(g,'db_pgsql', None)
if db is None:
    try:
        g.db_pgsql = psycopg2.connect("host=localhost dbname=xxx user=xxxx password=xxxx")
        return g.db_pgsql
    except Exception as e :
        print('Error')

else:
    print('Already connected before')
    return db

db = pgsql_connect()
cursor = db.cursor()
try:
    cursor.execute(" //Your SQL query// select * from Table1;")
    rows = cursor.fetchall()
    cursor.close()
    return rows
except Exception as e :
    print('unavailable')

Table1 in rows[].

(This is not a good solution for doing back up)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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