1. 程式人生 > >從生產環境的postgre資料庫伺服器備份資料庫並恢復資料庫到本地

從生產環境的postgre資料庫伺服器備份資料庫並恢復資料庫到本地

一、從生產環境的postgre資料庫伺服器備份資料庫
1、開始-執行-cmd 彈出dos控制檯
2、在控制檯裡,進入PostgreSQL安裝路徑的bin目錄下:指令:cd C:\Program Files\PostgreSQL\9.0\bin

3、pg_dump -h (postgre_server) -U (postgre_username) (databasename) > (C:\databasename.bak)

4、輸入指令:即為postgre_server伺服器的連結密碼

指令解釋:
1)pg_dump 是備份資料庫命令,
2)postgre_server是postgre伺服器的ip地址(必須保證資料庫允許外部訪問的許可權)當然本地的資料庫ip寫localhost;
3)postgre_username是資料庫的使用者名稱
4)databasename 是資料庫名。
5)> 意思是匯出到C:\databasename.bak檔案裡
(如果沒有寫路徑,單單寫databasename.bak檔名,那麼備份檔案會儲存在C: \Program Files\PostgreSQL\9.0\bin 資料夾裡。)

5、等待執行結束,進入以上對應目錄即可看到備份檔案databasename.bak

一、將備份資料庫檔案匯入至本地postgre資料庫
1、在本地postgre伺服器中新建資料庫new_databasename

2、開始-執行-cmd 彈出dos控制檯

3、在控制檯裡,進入PostgreSQL安裝路徑的bin目錄下:指令:cd C:\Program Files\PostgreSQL\9.0\bin

4、執行命令:psql -h (localhost) -U (postgre_username) -d (new_databasename) < (databasename.bak)

指令解釋:
1)psql是恢復資料庫命令
2)localhost是要恢復到哪個資料庫的地址,當然你可以寫上ip地址,也就是說能遠端恢復(必須保證 資料庫允許外部訪問的許可權)
3)postgre_username是要恢復到哪個資料庫的使用者;
4)new_databasename是要恢復到哪個資料庫
5)<  的意思是把C:\databasename.bak檔案匯入到指定的資料庫new_databasename裡。

5、輸入指令:即為localhost資料庫伺服器的連結密碼
6、等待執行結束,整個過程完畢,新的資料庫即可使用

7、以上恢復時報錯:postgres匯入備份出現'無效的命令\N'
解決方法:使用custom格式匯出,然後用pg_restore匯入。
匯出:pg_dump -F custom -U username -d dbname -h host -p port -f filepath
匯入:pg_restore -d dbname -U username -h host -p port --jobs=4 --verbose filepath