我需要从一个PostgreSQL数据库的多个表中提取SQL文件。目前我想到的方法如下:
pg_dump -t 'thr_*' -s dbName -U userName > /home/anik/psqlTest/db_dump.sql
然而,正如您所看到的,以前缀
thr
开头的所有表都被导出到一个统一的文件(db_dump.sql
)中。我总共有近90个表需要提取SQL,因此必须将数据存储到单独的文件中。请问我该怎么做?提前感谢您的帮助。
我需要从一个PostgreSQL数据库的多个表中提取SQL文件。目前我想到的方法如下:
pg_dump -t 'thr_*' -s dbName -U userName > /home/anik/psqlTest/db_dump.sql
thr
开头的所有表都被导出到一个统一的文件(db_dump.sql
)中。我总共有近90个表需要提取SQL,因此必须将数据存储到单独的文件中。pg_dump
命令多次,在循环期间每次替换表格名称。for table in table1 table2 table3 etc;
do pg_dump -t $table -U userName dbName > /home/anik/psqlTest/db_dump_dir/$table.sql;
done;
编辑:这种方法可以通过运行psql查询并将结果馈入循环中来动态获取表列表,而不是使用硬编码的列表:
for table in $(psql -U userName -d dbName -t -c "Select table_name From information_schema.tables Where table_type='BASE TABLE' and table_name like 'thr_%'");
do pg_dump -t $table -U userName dbName > /home/anik/psqlTest/db_dump_dir/$table.sql;
done;
这里的psql -t -c "SQL"
运行SQL
并输出结果,没有头部或页脚;由于只选择了一列,每行输出中都会有一个表名,被$(command)
捕获,你的shell将逐个循环遍历它们。
toc.dat
文件,目录中没有其他文件... - Rafs--schema-only
不会生成多个文件,而是生成一个包含数据库定义的文件... - Rafs(声望不够,无法评论正确的帖子) 我使用了您的脚本,并进行了一些更正和修改,可能对其他人有用:
#!/bin/bash
# Config:
DB=rezopilotdatabase
U=postgres
# tablename searchpattern, if you want all tables enter "":
P=""
# directory to dump files without trailing slash:
DIR=~/psql_db_dump_dir
mkdir -p $DIR
TABLES="$(psql -d $DB -U $U -t -c "SELECT table_name FROM
information_schema.tables WHERE table_type='BASE TABLE' AND table_name
LIKE '%$P%' ORDER BY table_name")"
for table in $TABLES; do
echo backup $table ...
pg_dump $DB -U $U -w -t $table > $DIR/$table.sql;
done;
echo done
我认为您在pg_dumb命令中忘记添加$DB变量,我添加了一个-w选项,对于自动化脚本来说,最好不要有密码提示,所以我创建了一个~/.pgpass文件并将我的密码保存在其中。我还给出了用户名,以便命令知道在.pgpass中获取哪个密码。希望这能帮助到某些人。
#!/bin/bash
# Config:
DB=dbName
U=userName
# tablename searchpattern, if you want all tables enter "":
P=""
# directory to dump files without trailing slash:
DIR=~/psql_db_dump_dir
mkdir -p $DIR
AUTH="-d $DB -U $U"
TABLES="$(psql $AUTH -t -c "SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_name LIKE '%$P%' ORDER BY table_name")"
for table in $TABLES; do
echo backup $table ...
pg_dump $AUTH -t $table > $DIR/$table.sql;
done;
echo done
pg_restore
从中提取各个表。 - IMSoP