PostgreSQL 數據庫的備份sql
1、創建數據庫鏈接數據庫
命令: psql -h IP地址 -p 端口 -U 數據庫用戶名 -d 數據庫名安全
psql -h 127.0.0.1 -p 5432 -U postgres -d postgres服務器
psql命令鏈接選項less
Connection options:ide
-h, --host=HOSTNAME 主機 默認local函數
-p, --port=PORT 端口 默認5432post
-U, --username=USERNAME 用戶名 默認postgresthis
-w, --no-password 從不提示密碼spa
-W, --password 強制 psql 提示輸入密碼,即便沒有密碼也會提示。
-d 指定要鏈接的庫名
=============================================
2、數據備份還原
pg_restore能夠恢復由pg_dump備份的文件,它會從新生成包括數據在內的全部用戶定義的類型、函數、表、索引的全部別要的命令
使用-d選項執行數據庫的名稱,-C指定備份文件的路徑
pg_restore -d testdb -U postgres -C /home/postgres/testdb.sql
psql是一個PostgreSQL的終端,它能夠運行用戶輸入的語句,輸入的語句還能夠來自一個文件,
因此對於備份的包含create、insert語句的文本文件,可使用psql恢復到數據中。
psql -d testdb -U postgres -f /home/postgres/testdb.sql
1.pg_dump備份數據庫
命令:pg_dump -h IP地址 -p 端口 -U 數據庫用戶名 -f 目標存儲文件及路徑 目標數據庫名
備份testdb數據庫到/home/postgres/testdb.sql文件
pg_dump -U postgres -f /home/postgres/testdb.sql testdb
恢復
psql -U postgres -d testdb -f /home/postgres/testdb.sql
備份testdb庫中的pmp_login_log表
pg_dump -U postgres -t pmp_login_log -f /home/postgres/login_log.sql testdb
恢復
psql -U postgres -d testdb -f /home/postgres/login_log.sql
2.pg_dumpall備份數據庫
使用pg_dumpall備份整個服務器的數據庫
備份
pg_dumpall -U postgres -f /home/postgres/postgres.sql
恢復
psql -U postgres -f /home/postgres/postgres.sql
3、PostgreSQL 無須手動輸入密碼
PostgreSQL裏沒有加入密碼選項,通常備份命令須要手動輸入密碼,因此會給自動備份帶來必定的不便。
查看了官方文檔,(英文很差,全程都翻譯/(ㄒoㄒ)/~~)
PGPASSWORD behaves the same as the password connection parameter. Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using the ~/.pgpass file (see Section 32.15).
PGPASSFILE specifies the name of the password file to use for lookups. If not set, it defaults to ~/.pgpass (see Section 32.15).
On Unix systems, the permissions on.pgpassmust disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.
文檔中提到兩種方法;
第一種方法:經過PostgreSQL的環境變量參數來實現保存密碼。
export PGPASSWORD="123456"
第二種方法:建立 ~/.pgpass 文件來保存密碼
密碼文件的格式: hostname:port:database:username:password
cat ~/.pgpass
localhost:5432:testdb:postgres:123456
注意:根據官方文檔的說明,由於安全的緣由,不推薦環境變量的方式,
推薦使用~/.pgpass 來保存密碼,此文件必須設置0600權限,若是權限不那麼嚴格,則該文件將被忽略。
chmod 0600 ~/.pgpass