使用Python的Postgresql数据库备份 [英] Postgresql Database Backup Using Python

查看:217
本文介绍了使用Python的Postgresql数据库备份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python代码备份数据库。我想备份一些相关数据表。如何使用 SELECT语句备份以及如何选择所需的表?

I would like to backup database using Python code. I want to backup some tables of related data. How to backup and how to choose desired tables using "SELECT" statement?

例如

我想获取2014年5月1日至2014年5月10日之间的数据,并将结果输出为.sql扩展文件

I want to get data from 2014-05-01 to 2014-05-10 of some tables and output this result as .sql extension file

如何使用python代码获取此格式?
如果您不介意,请解释。
谢谢。

How can I get this format using python code? If you don't mind, please explain. Thanks.

推荐答案

使用psycopg2建立数据连接。文档中有很多示例:

Use psycopg2 to establish the data connection. There are quite a few examples in the documentation:

http:/ /initd.org/psycopg/

配置好数据源后,遍历 SELECT语句的结果,以构建 INSERT INTO通过将结果集打印到文件中的语句。基本上是一些反向逻辑。

Once you have your data source configured, iterate through the results of your "SELECT" statement building a "INSERT INTO" statement via printing the result set to a file. Basically some reverse logic.

这样,如果时间到了,您需要使用备份文件,则只需运行SQL文件即可将数据重新插入。

That way, if the time comes and you need to use your backup file, you simple run the SQL file which inserts the data back in...

示例:

        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

干杯,

这篇关于使用Python的Postgresql数据库备份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆