簡體   English   中英

使用 Python 備份 Postgresql 數據庫

[英]Postgresql Database Backup Using Python

我想使用 Python 代碼備份數據庫。 我想備份一些相關數據的表。 如何使用“SELECT”語句備份以及如何選擇所需的表?

例如

我想獲取一些表的 2014-05-01 到 2014-05-10 的數據,並將這個結果輸出為 .sql 擴展文件

如何使用 python 代碼獲取這種格式? 如果你不介意,請解釋一下。 謝謝。

使用 psycopg2 建立數據連接。 文檔中有不少例子:

http://initd.org/psycopg/

配置數據源后,通過將結果集打印到文件來遍歷“SELECT”語句的結果,構建“INSERT INTO”語句。 基本上是一些反向邏輯。

這樣,如果時間到了並且您需要使用備份文件,您只需運行 SQL 文件,將數據插入回...

例子:

        import psycopg2
        import sys


        con = None

        try:

            con = psycopg2.connect(database='local', user='local', password='local',port='1970')
            cur = con.cursor()
            cur.execute('SELECT x FROM t')
            f = open('test.sql', 'w')
            for row in cur:
              f.write("insert into t values (" + str(row) + ");")
        except psycopg2.DatabaseError, e:
            print 'Error %s' % e
            sys.exit(1)
        finally:
            if con:
                con.close()

然后恢復:

psql <dbname> <username> < test.sql

干杯,

如果您的操作系統是 Linux,您可以使用下面的代碼。 首先,您應該運行apt-get install postgresql


def create_essentials():
    yaml_file = open("settings.yaml", 'r')
    settings = yaml.load(yaml_file)
    db_name = settings["db_name"]
    db_user = settings["db_user"]
    db_password = settings["db_password"]
    db_host = settings["db_host"]
    db_port = settings["db_port"]
    backup_path = settings["backup_path"]
    filename = settings["filename"]
    filename = filename + "-" + time.strftime("%Y%m%d") + ".backup"
    command_str = str(db_host)+" -p "+str(db_port)+" -d "+db_name+" -U "+db_user
    return command_str, backup_path, filename


def backup_database(table_names=None):
    command_str,backup_path,filename = create_essentials()
    command_str = "pg_dump -h "+command_str

    if table_names is not None:
        for x in table_names:
            command_str = command_str +" -t "+x

    command_str = command_str + " -F c -b -v -f '"+backup_path+"/"+filename+"'"
    try:
        os.system(command_str)
        print "Backup completed"
    except Exception as e:
        print "!!Problem occured!!"
        print e

def restore_database(table_names=None):
    command_str,backup_path,filename = create_essentials()
    command_str = "pg_restore -h "+command_str

    if table_names is not None:
        for x in table_names:
            command_str = command_str +" -t "+x

    command_str = command_str + " -v '"+backup_path+"/"+filename+"'"
    
    try:
        os.system(command_str)
        print "Restore completed"
    except Exception as e:
        print "!!Problem occured!!"
        print e

我想到的第一個想法是調用pg_dump命令轉儲您的表,類似於此處介紹的方法(但 google 有很多替代方法)。

但是,由於您的備份策略要求您選擇精確的日期而不僅僅是表格,您可能不得不依賴於一系列查詢,然后我的建議是使用像Psycopg這樣的庫。

編輯

我無法提供完整的示例,因為我不知道:

  • 你想轉儲哪些表
  • 每個表的精確備份策略是什么(即SELECT語句)
  • 您希望如何恢復它們。 通過刪除表然后重新創建它,通過覆蓋基於 ID 屬性的數據庫行,...

以下示例生成一個文件,用於存儲單個查詢的結果。

import psycopg

conn = psycopg2.connect("dbname=test user=postgres")  # change this according to your RDBMS configuration
cursor = conn.cursor()

table_name='YOUR_TABLE_HERE'  # place your table name here
with open("table_dump.sql") as f:
    cursor.execute("SELECT * FROM %s" % (table_name))  # change the query according to your needs
    column_names = []
    columns_descr = cursor.description
    for c in columns_descr:
        column_names.append(c[0])
    insert_prefix = 'INSERT INTO %s (%s) VALUES ' % (table_name, ', '.join(column_names))
    rows = cursor.fetchall()
    for row in rows:
    row_data = []
        for rd in row:
            if rd is None:
                row_data.append('NULL')
            elif isinstance(rd, datetime.datetime):
                row_data.append("'%s'" % (rd.strftime('%Y-%m-%d %H:%M:%S') ))
            else:
                row_data.append(repr(rd))
    f.write('%s (%s);\n' % (insert_prefix, ', '.join(row_data)))  # this is the text that will be put in the SQL file. You can change it if you wish.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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