我想将整个数据库导出到aws S3以便以后导入到BI工具中。我需要将每个数据库表导出到自己的csv文件中。但我不想手动做或做一些脚本。 MySQL have something for this。有没有一种简单的方法来实现Postgresql?
答案 0 :(得分:3)
使用此查询,您可以列出架构public
中的所有表:
select table_schema, table_name
from information_schema.tables
where table_type = 'BASE TABLE'
and table_schema = 'public';
您可以在函数中使用查询,该函数将为每个table_name执行适当的copy
命令:
create or replace function copy_my_tables ()
returns void language plpgsql as $$
declare
r record;
begin
for r in
select table_schema, table_name
from information_schema.tables
where table_type = 'BASE TABLE'
and table_schema = 'public'
loop
execute format ('copy %s.%s to ''c:\data\%s_%s.csv'' (format csv)',
r.table_schema, r.table_name, r.table_schema, r.table_name);
end loop;
end $$;
select copy_my_tables();
答案 1 :(得分:0)
我们可以使用bash脚本中的Header和bash脚本
将所有表导出到单独的csv中#set -x
read -p "Please provide Schema name " Schema
if [ -z $Schema ]
then
echo "No Schema name provided set default schema public."
Schema=public
fi
read -p "Please provide Database name " Db
if [ -z $Db ]
then
echo "No Database name provided set default database postgres."
Db=postges
fi
read -p "Please provide Postgres Role/User name " User
if [ -z $User ]
then
echo "No User/Role name provided set default User?Role postgres."
User=postgres
fi
echo " Schema Name is-->$Schema Database Name--> $Db User Name-->$User "
psql -U $User -h localhost -Atc "select tablename from pg_tables where schemaname='$Schema'" $Db |\
while read TABLENAME; do
echo "$TABLENAME"
psql -U $User -h localhost -c "COPY $Schema.$TABLENAME TO STDOUT WITH CSV HEADER" $Db > $TABLENAME.csv
done
在上面提到的脚本中你必须提供 架构 数据库和 用户/角色 如果需要提供端口和主机名,则可以使用-p和-h Option