2009-08-28 6522 views

回答

39

PostgreSQL不支持存儲NULL(\ 0×00)的文本字段中的字符(這是從數據庫NULL值,這是完全支持的明顯不同)。

來源:http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-UESCAPE

如果你需要存儲的NULL字符,則必須使用BYTEA場 - 這應該存儲任何你想要的,但它不支持文本操作。

鑑於PostgreSQL不支持它的文本值,沒有好辦法讓它刪除它。您可以將數據導入到bytea中,然後使用特殊函數(perl或某些東西,也許?)將其轉換爲文本,但在加載之前在預處理中可能會更容易。

+0

實施例: 'CREATE TABLE store_bytes( 鍵INTEGER NOT NULL , data bytea NOT NULL );' – zengr 2015-10-05 23:45:27

1

可以首先將數據插入BLOB字段,然後複製到文本字段與folloing功能

CREATE OR REPLACE FUNCTION blob2text() RETURNS void AS $$ 
Declare 
    ref record; 
    i integer; 
Begin 
    FOR ref IN SELECT id, blob_field FROM table LOOP 

      -- find 0x00 and replace with space  
     i := position(E'\\000'::bytea in ref.blob_field); 
     WHILE i > 0 LOOP 
     ref.bob_field := set_byte(ref.blob_field, i-1, 20); 
     i := position(E'\\000'::bytea in ref.blobl_field); 
     END LOOP 

    UPDATE table SET field = encode(ref.blob_field, 'escape') WHERE id = ref.id; 
    END LOOP; 

End; $$ LANGUAGE plpgsql; 

-

SELECT blob2text(); 
15

剛出來的正則表達式空字節:

s/\x00//g; 
+1

是空字符串被視爲空字節?不會'replaceAll(「s/\ x00 // g」,「」)'導致用其他空值替換它們? – 2016-01-20 11:03:11

+2

空字符串不被視爲空字節。空字節值是實際字符,但不可見。 – 2017-05-02 16:35:25

4

如果您使用Java,則可以在插入之前替換x00個字符,如下所示:

myValue.replaceAll("\u0000", "") 

將溶液提供,並且通過喬鮑說明在下面的帖子:

https://www.postgresql.org/message-id/1171970019.3101.328.camel%40coppola.muc.ecircle.de

分別爲:

in Java you can actually have a "0x0" character in your string, and that's valid unicode. So that's translated to the character 0x0 in UTF8, which in turn is not accepted because the server uses null terminated strings... so the only way is to make sure your strings don't contain the character '\u0000'.

相關問題