postgresql 使用 pg_dump 仅从数据库中的一个表中获取插入语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2857989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:30:39  来源:igfitidea点击:

Using pg_dump to only get insert statements from one table within database

postgresql

提问by Elitmiar

I'm looking for a way to get all rows as INSERTstatements from one specific table within a database using pg_dumpin PostgreSQL.

我正在寻找一种方法,可以INSERT使用pg_dumpPostgreSQL将所有行作为语句从数据库中的一个特定表中获取。

E.g., I have table A and all rows in table A I need as INSERTstatements, it should also dump those statements to a file.

例如,我有表 A 和表 AI 中的所有行都需要作为INSERT语句,它还应该将这些语句转储到文件中。

Is this possible?

这可能吗?

回答by psmears

if version < 8.4.0

如果版本 < 8.4.0

pg_dump -D -t <table> <database>

Add -abefore the -tif you only want the INSERTs, without the CREATE TABLE etc to set up the table in the first place.

添加-a-t,如果你只想要插入,而不CREATE TABLE等来设置表摆在首位。

version >= 8.4.0

版本 >= 8.4.0

pg_dump --column-inserts --data-only --table=<table> <database>

回答by James111

If you want to DUMP your inserts into an .sqlfile:

如果要将插入内容转储到.sql文件中:

  1. cdto the location which you want to .sqlfile to be located
  2. pg_dump --column-inserts --data-only --table=<table> <database> > my_dump.sql
  1. cd到您要.sql归档的位置
  2. pg_dump --column-inserts --data-only --table=<table> <database> > my_dump.sql

Note the > my_dump.sqlcommand. This will put everything into a sql file named my_dump

注意> my_dump.sql命令。这会将所有内容放入名为my_dump的 sql 文件中

回答by Pipo

Put into a script I like something like that:

放入我喜欢的脚本中:

#!/bin/bash
set -o xtrace # remove me after debug
TABLE=charge_unit
DB_NAME=prod_sit_entities_db

BASE_DIR=/var/backups/someDir
LOCATION="${BASE_DIR}/myApp_$(date +%Y%m%d_%H%M%S)"
FNAME="${LOCATION}_${DB_NAME}_${TABLE}.sql"

# Create backups directory if not exists
if [[ ! -e $BASE_DIR ]];then
|       mkdir $BASE_DIR
|       chown -R postgres:postgres $BASE_DIR
fi

sudo -H -u postgres pg_dump --column-inserts --data-only --table=$TABLE $DB_NAME > $FNAME
sudo gzip $FNAME

回答by Lenon Tolfo

just in case you are using a remote access and want to dump all database data, you can use:

以防万一您使用远程访问并想要转储所有数据库数据,您可以使用:

pg_dump -a -h your_host -U your_user -W -Fc your_database > DATA.dump

pg_dump -a -h your_host -U your_user -W -Fc your_database > DATA.dump

it will create a dump with all database data and use

它将创建一个包含所有数据库数据的转储并使用

pg_restore -a -h your_host -U your_user -W -Fc your_database < DATA.dump

pg_restore -a -h your_host -U your_user -W -Fc your_database < DATA.dump

to insert the same data in your data base considering you have the same structure

考虑到您具有相同的结构,在您的数据库中插入相同的数据