天天看點

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>