字符串常量
通过将单引号加倍来避开'
->;''
是标准的方法,当然有效:
'user's log' -- incorrect syntax (unbalanced quote)
'user''s log'
请注意,纯单引号(ASCII/UTF-8代码39)不是反勾号`
,它在Postgres中没有特殊用途(与某些其他RDBMS不同),也不是双引号"
,用于标识符.
在旧版本中,或者如果仍然使用standard_conforming_strings = off
运行,或者通常,如果在字符串前面加E
以声明Posix escape string syntax,也可以使用反斜杠\
转义:
E'user\'s log'
Backslash itself is escaped with another backslash. But that's generally not preferable.
If you have to deal with many single quotes or multiple layers of escaping, you can avoid quoting hell in PostgreSQL with dollar-quoted strings:
'escape '' with '''''
$$escape ' with ''$$
为了进一步避免美元报价之间的混淆,请为每对货币添加一个唯一的标记:
$token$escape ' with ''$token$
可以嵌套任意数量的级别:
$token2$Inner string: $token1$escape ' with ''$token1$ is nested$token2$
请注意,$
个字符在您的客户端软件中是否具有特殊意义.此外,你可能还得逃离它.对于标准的PostgreSQL客户机,如psql或pgAdmin,情况并非如此.
这对于编写plpgsql函数或特殊SQL命令非常有用.然而,当用户输入是可能的时,它不能减轻使用预先准备好的语句或其他方法来防止应用程序中的SQL注入的需要.@Craig's answer还有更多.更多详情:
博士后的价值观
在处理数据库中的值时,有几个有用的函数可以正确引用字符串: