postgresql - 如何使用纯文本脚本插入(来自文件数据的原始字节)

标签 postgresql character-encoding

数据库:Postgres 9.1

我有一个名为 logos 的表,定义如下:

create type image_type as enum ('png');
create table logos (
  id UUID primary key,
  bytes bytea not null,
  type image_type not null,
  created timestamp with time zone default current_timestamp not null
);
create index logo_id_idx on logos(id);

我希望能够以两种方式将记录插入到该表中。

在表中插入行的第一种(也是最常见的)方式是用户通过 html 文件上传表单提供 PNG 图像文件。在服务器上处理请求的代码将收到一个包含 PNG 图像文件中数据的字节数组,并使用与所解释的内容非常相似的内容在表中插入一条记录 here .在互联网上有很多关于如何将字节数组插入 bytea 类型的 postgresql 字段的示例。这是一个简单的练习。插入代码的示例如下所示:

insert into logos (id, bytes, type, created) values (?, ?, ?, now()) 

字节将被设置为:

...
byte[] bytes = ... // read PNG file into a byte array.
...
ps.setBytes(2, bytes);
...

第二种方式 将行插入表中的方法是来自纯文本文件 脚本。需要这样做的原因只是为了将测试数据填充到表中以进行自动化测试,或者为远程开发环境使用一些记录来初始化数据库。

无论数据如何输入表中,应用程序显然需要能够从表中选择 bytea 数据并将其转换回 PNG 图像。


问题

如何正确编码一个字节数组,以便能够从脚本中插入数据,以便只有文件中包含的原始字节存储在数据库中?

我可以编写代码来读取文件并吐出插入语句来填充脚本。但是我不知道如何对纯文本脚本的字节数组进行编码,这样当从 psql 运行脚本时,图像数据将与使用 setBytes jdbc 代码插入的文件相同.

我想用这样的东西运行脚本:

psql -U username -d dataBase -a -f test_data.sql

最佳答案

IMO 在 SQL 文件中表示 bytea 数据的最简单方法是使用 hex format :

8.4.1. bytea Hex Format

The "hex" format encodes binary data as 2 hexadecimal digits per byte, most significant nibble first. The entire string is preceded by the sequence \x (to distinguish it from the escape format). In some contexts, the initial backslash may need to be escaped by doubling it, in the same cases in which backslashes have to be doubled in escape format; details appear below. The hexadecimal digits can be either upper or lower case, and whitespace is permitted between digit pairs (but not within a digit pair nor in the starting \x sequence). The hex format is compatible with a wide range of external applications and protocols, and it tends to be faster to convert than the escape format, so its use is preferred.

Example:

SELECT E'\\xDEADBEEF';

将字节数组转换为十六进制对于一个理智的人(比如你自己)用来编写 SQL 文件生成器的任何语言来说都是微不足道的。

关于postgresql - 如何使用纯文本脚本插入(来自文件数据的原始字节),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21592609/

相关文章:

php - 如何在 PostgreSQL 中实现循环

jsp - 以EL方式设置字符编码

java - JOOQ Maven 插件 - 生成源文件的编码

mysql - 导轨 3 : Change charset and collation of an existing mysql database

java - 通过java.nio写一个带有BOM的UTF-8编码的文本文件

node.js - PostgreSQL 中跨多个时区的总时差

postgresql - Phoenix/Ecto - 查询字符串数组中的匹配项

go - 电子邮件主题、标题在不同字符集中解码,如 ISO-2022-JP、GB-2312 等

sql - 如何在 postgresql 中排除上下文引发异常

sql - 在 PostgreSQL 中内部连接表时计数缓慢