如何将(文件)数据插入PostgreSQL bytea列?

这个问题不是关于bytea v.oy v.blobs v.大对象等.

我有一个包含主键整数字段和bytea字段的表.我想将数据输入bytea字段.据推测,这可以通过其中一种PL /语言来完成,我可能会考虑将来使用PL / Python来做这件事.

由于我还在测试和试验,我只想使用“标准”sql语句从文件(在服务器上)插入数据.我知道只有在服务器上具有写权限的管理员才能以我想要的方式插入数据.我不关心这个阶段,因为用户目前不会插入bytea数据.我一直在搜索各种StackExchange网站,Postgresql档案馆和互联网,但一直未能找到答案.

编辑:从2008年开始的This讨论意味着我想做的事情是不可能的.那么如何使用bytea字段?

编辑:This 2005年的类似问题仍未得到答复.

解决:psycopg网站上提供的详细信息here提供了我用Python编写的解决方案的基础.也可以使用PL / Python将二进制数据插入到bytea列中.我不知道使用“纯”sql是否可行.

作为超级用户
create or replace function bytea_import(p_path text,p_result out bytea) 
                   language plpgsql as $$
declare
  l_oid oid;
begin
  select lo_import(p_path) into l_oid;
  select lo_get(l_oid) INTO p_result;
  perform lo_unlink(l_oid);
end;$$;

lo_get是在9.4中引入的,因此对于旧版本,您需要:

create or replace function bytea_import(p_path text,p_result out bytea) 
                   language plpgsql as $$
declare
  l_oid oid;
  r record;
begin
  p_result := '';
  select lo_import(p_path) into l_oid;
  for r in ( select data 
             from pg_largeobject 
             where loid = l_oid 
             order by pageno ) loop
    p_result = p_result || r.data;
  end loop;
  perform lo_unlink(l_oid);
end;$$;

然后:

insert into my_table(bytea_data) select bytea_import('/my/file.name');

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...