postgresql 中的字符串文字和转义字符
-
08-06-2019 - |
题
尝试将转义字符插入表中会导致警告。
例如:
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');
这抑制了警告,但文本仍然没有正确返回。当我按照迈克尔的建议添加额外的斜杠时,它起作用了。
像这样:
insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
其他提示
凉爽的。
我还找到了有关 E 的文档:
http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
PostgreSQL 还接受“转义”字符串常量,这是 SQL 标准的扩展。通过在左单引号之前写入字母 E(大写或小写)来指定转义字符串常量,例如E'foo'。(当跨行继续转义字符串常量时,仅在第一个左引号之前写入 E。)在转义字符串中,反斜杠字符 (\) 开始类似 C 的反斜杠转义序列,其中反斜杠和后续字符的组合( s) 代表一个特殊的字节值。\b 是退格键,\f 是换页符, 是换行符, 是回车符, 是制表符。还支持 \digits(其中digits 表示八进制字节值)和\xhexdigits(其中hexdigits 表示十六进制字节值)。(您有责任确保您创建的字节序列是服务器字符集编码中的有效字符。)反斜杠后面的任何其他字符均按字面意思处理。因此,要包含反斜杠字符,请写入两个反斜杠 (\\)。此外,除了正常的 '' 方式之外,还可以通过编写 \' 将单引号包含在转义字符串中。
由于您在字符串中使用反斜杠,因此发出警告。如果您想避免出现该消息,请键入此命令“set standard_conforming_strings=on;”。然后在字符串前使用“E”,包括您希望 postgresql 解释的反斜杠。
我发现 Postgres 不太可能在输入时截断您的数据 - 它要么拒绝它,要么按原样存储它。
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, e.g., E'\r\n'.
INSERT 0 1
milen=> select * from EscapeTest;
text
------------------------
This will be inserted
This will not be
(1 row)
milen=>
真是愚蠢的问题:您确定字符串被截断,而不仅仅是在您指定的换行符处被破坏(并且可能不会在您的界面中显示)?即,您希望该字段显示为
这将被插入 n这不会
或者
这将被插入
这不会是
另外,你用的是什么接口?有没有可能一路上有什么东西正在吃掉你的反斜杠?