在批处理脚本中调用psql pg_dump命令

时间:2014-01-29 14:13:34

标签: postgresql batch-file

我正在尝试在批处理文件中调用pg_dump命令。首先,我获取所有表名,然后循环每个表并执行pg_dump命令。它可能是这样的,但我得到一个错误作为“语法错误”:

for %%T in (psql -U postgres -w -d test_db -t -c "SELECT table_name FROM
information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'")
do pg_dump -t %%T -U postgres test_db -w -f "C:\Users\mtuna\Documents\dumpfiles\%%T.sql"
done;

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

这是一个解决方案:

@echo off
SET TableListeFile=C:\Users\mtuna\Documents\dumpfiles\database_list.txt

REM Saveing all tables name of database test_db on a temp file: database_list.txt  
psql -U postgres  -d test_db -t -c "SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'" -o "%TableListeFile%"

REM Loop on liste tables name:
FOR /F "tokens=*" %%I IN (%TableListeFile%) DO (
REM Dump each table on file
pg_dump  -U postgres -h localhost -t %%I test_db > "C:\Users\mtuna\Documents\dumpfiles\%%I.sql"
)
REM Delete temp file
del /Q %TableListeFile%

它会提示您输入每个转储的密码。如果您不想接受承诺,可以使用Pgpass File

希望有所帮助。

胡阿里·

答案 1 :(得分:1)

备份:batch_file_backup.bat

@echo off
SET PGPATH="E:\PostgreSQL\9.5\bin\pg_dump.exe"
SET PGPASSWORD=admin
%PGPATH% -h 127.0.0.1 -p 5432  -U postgres -F c -b -v -f  C:\Users\Pukar\Downloads\backupfile\2017-04-04.backup database_name

蝙蝠文件备份运行PHP代码:

$batchfile_path = "E:/xampp/htdocs/yig2016/ybase/main_app/bizlayer/protected/batch_file_backup.bat";
$WshShell       = new COM("WScript.Shell");
$exec           = $WshShell->Run($batchfile_path, 0, false);

<强>恢复:batch_file_restore.bat

@echo off
SET PGPATH="E:\PostgreSQL\9.5\bin\pg_restore.exe"
SET PGPASSWORD=admin
%PGPATH% -h 127.0.0.1 -p 5432 -U postgres -d database_name -v C:\Users\Pukar\Downloads\backupfile\2017-04-04.backup

Bat文件还原运行PHP代码:

$batchfile_path = 
E:/xampp/htdocs/yig2016/ybase/main_app/bizlayer/protected/batch_file_restore.bat";
$WshShell       = new COM("WScript.Shell");
$exec           = $WshShell->Run($batchfile_path, 0, false);

参考文献: http://www.somelesson.blogspot.com/2017/04/postgresql-backup-and-restore.html