在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:35:01  来源:igfitidea点击:

Escaping backslash in Postgresql

postgresqlescapingfilepathslash

提问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=onand use:

或者你可以set standard_conforming_strings=on使用:

select '\CAD_SVR\CADJOBS12-CEDARHURST/ ELEMENTARY SCHOOL12-20.DWG';

\CAD_SVR\CADJOBS12-CEDARHURST/ ELEMENTARY SCHOOL12-20.DWG

quote_literalfunction should be used only when you will be constructing a query for execcall in pl/pgsql function. For constructing a query in a client you should use a client's library quoting function, like PQescapeStringConnin libpq or pg_escape_stringin 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_stringPHP 中。但最好的选择是使用准备好的语句并使用字符串作为参数,这样可以消除所有引用并且更安全

回答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.

我暂时推荐双反斜杠。