Reputation: 1
I'm newbie to python and sql.
Could anyone please suggest a solution? 🙏🙏🙏
Upvotes: 0
Views: 3408
Reputation: 39
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)
Upvotes: 0