2014-05-19 73 views
1

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

例如

我想從2014-05-01到數據的一些表和輸出的2014年5月10日這個結果作爲.sql擴展文件

?我怎樣才能使用Python代碼這種格式? 如果您不介意,請解釋。 謝謝。

回答

2

使用psycopg2建立數據連接。有文檔中相當多的例子:

http://initd.org/psycopg/

一旦配置數據源,通過你的「選擇」的結果重複說明建立一個通過打印結果設置爲「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 

乾杯,

+0

寫入「insert into」語句的建議是爲了將該代碼寫入文本文件,而不是從PsycoPG調用。開始的時候我對答案有些困惑。你應該做一些像http://stackoverflow.com/a/2771803/582906 – furins

+0

我不認爲你明白。一旦您使用SELECT從表中提取數據,您可以對該數據執行任何操作。我說的是你可以將SELECT轉換爲INSERT,這很簡單。 另外,如果您再次閱讀問題,他想要備份的數據的邏輯子集,而不是物理本身。 您可以使用pg_dump -t

等來完成此操作,只需使用他所要求的數據子集創建備份表即可。 – d1ll1nger

+1

當然,我明白了,我的答案從一開始就提供了使用自定義查詢而不是pg_dump的想法。我只是說,你的答案的第一個版本可能會導致一些混淆(也許是我的),現在我相信,由於一些代碼,兩者都有所改進。 – furins

1

我想到的第一個想法是轉儲您的表,調用pg_dump命令,類似於here(但谷歌是很多選擇)的方法。

但是,由於您的備份策略要求您選擇精確日期而不僅僅是表格,您可能不得不依賴於一系列查詢,然後我的建議是使用類似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. 
+0

如何獲得通過Psycopg庫我的結果。如果我使用這個庫,我得到示例'SELECT'查詢結果...但我真的想.sql文件就像導出文件的phpmyadmin ..稍後..我會重用這個.sql文件通過導入文件恢復。這就是爲什麼......我不知道如何用python語言編寫這段代碼......如果你不介意,請給出一些示例代碼。謝謝。 – sharipha

+0

我明白了。謝謝。 :) – sharipha

+0

@sharipha,我可以使用psycopg2轉儲數據庫嗎? –

1

如果你的操作系統是Linux,你可以使用代碼belove 首先你應該運行 「apt-get的安裝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