[英]Generate postgresql database backup using python
我是python和sql的新手。
有人可以提出解决方案吗? 🙏🙏🙏
您的需求不是很清楚,请提供有关您的环境的更多信息。 为什么不真正使用python呢? 您可以使用pg_dump工具并使用bash脚本设置计时器或均匀性吗?
pg_dump dbname > dbname.bak
您可以恢复旧数据库.bak:
psql dbname < dbname.bak
无需sql。
如果您确实需要使用python和SQL查询来执行此操作,请使用psycopg2库建立连接并执行一些SQL查询:
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在[[]行中。
(这不是备份的好方法)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.