0

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? 🙏🙏🙏

1 Answer 1

0

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)

Sign up to request clarification or add additional context in comments.

2 Comments

To add to this excellent answer - using queries like that to perform a database backup has the drawback of being slower, and not backing up the structure of the tables.
Yes, constraints, functions is not extractable in SQL, defenitely not a good solution ^^

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.