天天看点

PostgreSQL Oracle 兼容性之 - ASCIISTR

在oracle中有一个函数asciistr,可以将非ascii字符转换成utf-16编码的字符,因此转换后的字符串可以存储在只支持ascii编码的数据库中。

asciistr takes as its argument a string, or an expression that resolves to a string, in any character set and returns an ascii version of the string in the database character set.

non-ascii characters are converted to the form \xxxx, where xxxx represents a utf-16 code unit.

例子

\00c4即转换后的utf-16编码,这样整个字符串就可以存储在ascii编码的数据库中了。

了解了asciistr的目的之后,我们就可以在postgresql中实现对非ascii编码的字符转换了。

postgresql数据库没有utf-16字符集,但是它支持utf-8,utf-8是变长字符集,支持全球所有的语言字符编码。

postgresql提供了几个转换函数如下

例子,支持来回转换

方法2,使用textsend函数,这个函数没有编码输入,所以需要设置client_encoding。

postgresql支持的字符编码转换函数在这里

以上例子把整个字符串都进行了转换,包括一些已经是ascii的字符也被转换了,转换后长度变长了,如果你要尽量缩小长度怎么办呢?

如果你要对一个字符串中非ascii字符转换为bytea,而ascii字符保持不变,则需要自定义postgresql函数,如下demo

测试

你还可以输出字符串,也可以直接输出字符串

使用这种方法,在反转换时,也要通过函数来处理。

反转转换举例

<a href="https://www.postgresql.org/docs/9.6/static/multibyte.html">https://www.postgresql.org/docs/9.6/static/multibyte.html</a>

<a href="http://info.flagcounter.com/h9v1">count</a>