我有一个名为:nyummy的数据库模式和一个名为cimory的表:
create table nyummy.cimory (
id numeric(10,0) not null,
name character varying(60) not null,
city character varying(50) not null,
CONSTRAINT cimory_pkey PRIMARY KEY (id)
);
我想将cimory表的数据导出为插入SQL脚本文件。但是,我只想导出城市等于“tokyo”的记录/数据(假设城市数据都是小写的)。
怎么做呢?
解决方案是使用免费的GUI工具还是命令行并不重要(尽管GUI工具解决方案更好)。我尝试过pgAdmin III,但我找不到这样做的选项。
我需要一种不需要创建临时表(在生产环境中)就可以生成插入语句的方法。我确实看到了上面的pg_dump的一些有用的参数,但最终还是设计了一种方法
生成插入语句并转储到文件中
下面的陈述很有用,我觉得对那些在这里找到类似答案的人会很有用。
$ /usr/local/bin/pg_dump -h the_db_host_address -d the_db_name --table=schema_name.table_name --data-only --column-inserts -U postgres -p the_port_number -v -f /Users/the_user/folder_name/insrt_stmts_file_name.sql
下一件事是一个提示,要求密码,在上面的情况下,我提供了postgres密码,但任何其他用户应该工作良好,具有读取能力。
我运行了文件中的插入语句:
insrt_stmts_file_name。在DBeaver客户端执行sql命令。
但同样可以从命令提示符运行,使用以下脚本:
/usr/local/bin/psql -h the_db_host_address -d the_db_name -v -U postgres -f /Users/the_user/folder_name/insrt_stmts_file_name.sql
pg_dump / psql标志的引用:
-h = host
-d = db name
-v = verbose(它会随着进程输出)
-U = db用户名
-f =文件/路径
我刚做了一个快速手术。它只适用于单行,因此我创建了一个临时视图,只选择我想要的行,然后替换pg_temp。temp_view和我想要插入的实际表。
CREATE OR REPLACE FUNCTION dv_util.gen_insert_statement(IN p_schema text, IN p_table text)
RETURNS text AS
$BODY$
DECLARE
selquery text;
valquery text;
selvalue text;
colvalue text;
colrec record;
BEGIN
selquery := 'INSERT INTO ' || quote_ident(p_schema) || '.' || quote_ident(p_table);
selquery := selquery || '(';
valquery := ' VALUES (';
FOR colrec IN SELECT table_schema, table_name, column_name, data_type
FROM information_schema.columns
WHERE table_name = p_table and table_schema = p_schema
ORDER BY ordinal_position
LOOP
selquery := selquery || quote_ident(colrec.column_name) || ',';
selvalue :=
'SELECT CASE WHEN ' || quote_ident(colrec.column_name) || ' IS NULL' ||
' THEN ''NULL''' ||
' ELSE '''' || quote_literal('|| quote_ident(colrec.column_name) || ')::text || ''''' ||
' END' ||
' FROM '||quote_ident(p_schema)||'.'||quote_ident(p_table);
EXECUTE selvalue INTO colvalue;
valquery := valquery || colvalue || ',';
END LOOP;
-- Replace the last , with a )
selquery := substring(selquery,1,length(selquery)-1) || ')';
valquery := substring(valquery,1,length(valquery)-1) || ')';
selquery := selquery || valquery;
RETURN selquery;
END
$BODY$
LANGUAGE plpgsql VOLATILE;
调用:
SELECT distinct dv_util.gen_insert_statement('pg_temp_' || sess_id::text,'my_data')
from pg_stat_activity
where procpid = pg_backend_pid()
我还没有对注入攻击进行测试,请让我知道quote_literal调用是否不够。
此外,它只适用于可以简单地转换为::text然后再转换回来的列。
这也是为了Greenplum,但我想不出为什么它不能在Postgres, CMIIW上工作的原因。