在postgresql中的string文字和转义字符

尝试将转义字符插入到表中会导致警告。

例如:

create table EscapeTest (text varchar(50)); insert into EscapeTest (text) values ('This is the first part \n And this is the second'); 

产生警告:

 WARNING: nonstandard use of escape in a string literal 

使用PSQL 8.2

任何人都知道如何解决这个问题?

部分。 文本被插入,但警告仍然生成。

我发现一个讨论表明文本需要在“E”之前,因此:

 insert into EscapeTest (text) values (E'This is the first part \n And this is the second'); 

这压制了警告,但文本仍然没有被正确地返回。 当我按照Michael的build议添加额外的斜线时,它就起作用了。

因此:

 insert into EscapeTest (text) values (E'This is the first part \\n And this is the second'); 

凉。

我还find了有关E:

http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS

PostgreSQL也接受“转义”string常量,这是SQL标准的扩展。 通过在开头的单引号之前写入字母E(大写或小写)来指定转义string常量,例如E'foo'。 (当在一行中继续使用一个转义string常量时,只在第一次打开引号之前写入E)。在转义string中,反斜线字符(\)开始一个类似C的反斜杠转义序列,其中反斜杠和后面的字符s)表示一个特殊的字节值。 \ b是退格符,\ f是换页符,\ n是换行符,\ r是回车符,\ t是一个制表符。 还支持\ digits,其中数字表示八进制字节值,\ xhexdigits,其中hexdigits表示hex字节值。 (您所负责的是您创build的字节序列是服务器字符集编码中的有效字符。)反斜杠后面的任何其他字符都是从字面上进行的。 因此,要包含一个反斜杠字符,写两个反斜杠(\\)。 此外,除了''的正常方式之外,通过书写\'可以将单引号包括在转义string中。

由于您在string中使用了反斜杠,因此发出警告。 如果要避免该消息,请input此命令“set standard_conforming_strings = on;”。 然后在你的string之前使用“E”,包括你想要postgresql来解释的反斜杠。

我发现Postgres不太可能在input时截断你的数据 – 要么拒绝它,要么按原样存储它。

 milen@dev:~$ psql Welcome to psql 8.2.7, the PostgreSQL interactive terminal. Type: \copyright for distribution terms \h for help with SQL commands \? for help with psql commands \g or terminate with semicolon to execute query \q to quit milen=> create table EscapeTest (text varchar(50)); CREATE TABLE milen=> insert into EscapeTest (text) values ('This will be inserted \n This will not be'); WARNING: nonstandard use of escape in a string literal LINE 1: insert into EscapeTest (text) values ('This will be inserted... ^ HINT: Use the escape string syntax for escapes, eg, E'\r\n'. INSERT 0 1 milen=> select * from EscapeTest; text ------------------------ This will be inserted This will not be (1 row) milen=> 

真的很愚蠢的问题:你确定string正在被截断,而不是在你指定的换行符处被破坏(并且可能没有在你的界面中显示)? 也就是说,你期望这个领域能performance出来吗?

这将被插入\ n这不会是

要么

这将被插入

这不会

另外,你使用什么接口? 是否有可能一路上正在吃你的反斜杠?