Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql Database Backup Using Python

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?

e.g.

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

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

like image 775
sharipha Avatar asked May 19 '14 08:05

sharipha


People also ask

How do I backup my Postgres database?

Backing up a PostgreSQL Database To back up your database onto a plain-text SQL file, simply login to your database server. Then switch to the Postgres account, and run the command. The plain-text SQL file will have the commands required to reconstruct the entire database to its state when backed up.

Which is an approach to backup PostgreSQL data?

There are three fundamentally different approaches to backing up PostgreSQL data: SQL dump. File system level backup. Continuous archiving.

Can Python connect to PostgreSQL?

How to Connect to PostgreSQL from Python? In order to connect to a PostgreSQL database instance from your Python script, you need to use a database connector library. In Python, you have several options that you can choose from. Some libraries that are written in pure Python include pg8000 and py-postgresql.


1 Answers

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

http://initd.org/psycopg/

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.

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...

Example:

        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()

Then to restore:

psql <dbname> <username> < test.sql

Cheers,

like image 121
d1ll1nger Avatar answered Oct 12 '22 13:10

d1ll1nger