介绍
这是一个更新的答案,它包括了如何插入和查询。
可以使用 decode
函数将十六进制转换为 bytea 值。这应该用于查询和插入操作。
这可以用于插入和查询。
SQL Fiddle 示例
查询现有数据
SELECT * FROM mytable WHERE testcol = (decode('013d7d16d7ad4fefb61bd95b765c8ceb', 'hex'));
查询中的编码与解码
一个用户提出了以下问题:
How does searching the bytea field by hex value after inserting it?
SELECT * FROM my_table WHERE myHexField =
(encode('013d7d16d7ad4fefb61bd95b765c8ceb', 'hex'));
does not work.
在文档
"二进制字符串函数和操作"中,他们对
encode
和
decode
进行了描述。
+==================================+=============+=======================================================================================================+=======================================+============+
| Function | Return Type | Description | Example | Result |
+==================================+=============+=======================================================================================================+=======================================+============+
| decode(string text, format text) | bytea | Decode binary data from textual representation in string. Options for format are same as in encode. | decode('123\000456', 'escape') | 123\000456 |
+----------------------------------+-------------+-------------------------------------------------------------------------------------------------------+---------------------------------------+------------+
| encode(data bytea, format text) | text | Encode binary data into a textual representation. Supported formats are: base64, hex, escape. escape | encode('123\000456'::bytea, 'escape') | 123\000456 |
| | | converts zero bytes and high-bit-set bytes to octal sequences (\nnn) and doubles backslashes. | | |
+----------------------------------+-------------+-------------------------------------------------------------------------------------------------------+---------------------------------------+------------+
因此,您会注意到Encode
用于将二进制数据编码为文本字符串,并返回文本。然而,由于我们存储的是bytea
,所以我们必须在插入和查询时使用decode
。
插入
create table mytable (testcol BYTEA);
INSERT INTO
mytable (testcol)
VALUES
(decode('013d7d16d7ad4fefb61bd95b765c8ceb', 'hex'));
来源:请看之前的回答
bytea
列。 - VSO