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.
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.
There are three fundamentally different approaches to backing up PostgreSQL data: SQL dump. File system level backup. Continuous archiving.
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.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With