在 Postgresql 中转义反斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3049034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping backslash in Postgresql
提问by mohnston
I'm trying to write an sql function in Postgresql that will parse a file path. I want to return just the file name.
我正在尝试在 Postgresql 中编写一个 sql 函数来解析文件路径。我只想返回文件名。
I cannot get past getting an accurate text string in the function.
我无法通过在函数中获取准确的文本字符串。
Here is the function:
这是函数:
Function: job_page("inputText" text)
DECLARE
text;
BEGIN
= quote_literal("inputText");
return ;
END
When I run this:
当我运行这个:
select job_page('\CAD_SVR\CADJOBS12-CEDARHURST ELEMENTARY SCHOOL12-20.DWG')
I get this result:
我得到这个结果:
"E'\CAD_SVRCADJOBSé2-CEDARHURST ELEMENTARY SCHOOLé2-20.DWG'"
Postgresql interprets the slash followed by certain characters as a special character.
Postgresql 将斜杠后跟某些字符解释为特殊字符。
How do I escape?
我该如何逃生?
回答by Tometzky
You should use escape string syntax:
您应该使用转义字符串语法:
select E'\CAD_SVR\CADJOBS\7512-CEDARHURST ELEMENTARY SCHOOL\7512-20.DWG';
\CAD_SVR\CADJOBS12-CEDARHURST ELEMENTARY SCHOOL12-20.DWG
This will work in any case.
这在任何情况下都有效。
Or you can set standard_conforming_strings=on
and use:
或者你可以set standard_conforming_strings=on
使用:
select '\CAD_SVR\CADJOBS12-CEDARHURST/ ELEMENTARY SCHOOL12-20.DWG';
\CAD_SVR\CADJOBS12-CEDARHURST/ ELEMENTARY SCHOOL12-20.DWG
quote_literal
function should be used only when you will be constructing a query for exec
call in pl/pgsql function. For constructing a query in a client you should use a client's library quoting function, like PQescapeStringConn
in libpq or pg_escape_string
in PHP. But the best option is to use prepared statements and use a string as an argument, which eliminates all quoting and is much safertoo.
quote_literal
仅当您将exec
在 pl/pgsql 函数中构造调用查询时才应使用该函数。要在客户端构建查询,您应该使用客户端的库引用函数,例如PQescapeStringConn
在 libpq 或pg_escape_string
PHP 中。但最好的选择是使用准备好的语句并使用字符串作为参数,这样可以消除所有引用并且更安全。
回答by Peter Tillemans
You have to escape the \ with another \
你必须用另一个 \ 来逃避 \
i.e. \\
IE \\
You can change this behavior off by setting the standard_conforming_strings option to on. By default it is off, but this default will change some time in the future.
您可以通过将standard_conforming_strings 选项设置为on 来关闭此行为。默认情况下它是关闭的,但这个默认值会在未来的某个时间改变。
I recommend the double backslash for the time being.
我暂时推荐双反斜杠。