簡體   English   中英

使用python生成Postgresql數據庫備份

[英]Generate postgresql database backup using python

我是python和sql的新手。

  1. 我想使用python腳本列出數據庫中的所有表
  2. 我想使用python為現有的postgresql表創建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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM