postgres逃脱角色

Cha*_*ris 9 postgresql

我是postgres的新手,如何在where子句的MESSAGE参数中转义RTF语法?

select count(*) 
from communicationoutgoingmessagescheduledetails 
where email='chris.green@waynesreaves.com' 
and message='{\rtf1\deff0{\fonttbl{\f0 Times New Roman;}}{\colortbl\red0\green0\blue0 ;\red0\green0\blue255 ;}{\*\listoverridetable}{\stylesheet {\ql\cf0 Normal;}{\*\cs1\cf0 Default Paragraph Font;}{\*\cs2\sbasedon1\cf0 Line Number;}{\*\cs3\ul\cf1 Hyperlink;}}\splytwnine\sectd\pard\plain\ql{\cf0 first }{\b\cf0 paymen}{\b\cf0 t bold }{\cf0 rem}{\cf0 inder}\par\pard\plain\ql{\ul\cf0 se}{\ul\cf0 cond PAYMENT }{\b\ul\cf0 reminder}\b\ul\par}' 
and succeddful=-1 
and senttime::timestamp::date='2/7/2013 12:00:00 AM'
Run Code Online (Sandbox Code Playgroud)

更新

这是我得到的错误

WARNING:  nonstandard use of escape in a string literal LINE 4: and message='{\rtf1\deff0{\fonttbl{\f0 Times New Roman;}}{\c...

HINT:  Use the escape string syntax for escapes, e.g., E'\r\n'. 
ERROR:  invalid Unicode escape LINE 4: and message='{\rtf1\deff0{\fonttbl{\f0 Times New Roman;}}{\c...

HINT:  Unicode escapes must be \uXXXX or \UXXXXXXXX.
********** Error **********

ERROR: invalid Unicode escape SQL state: 22025 Hint: Unicode escapes must be \uXXXX or \UXXXXXXXX. Character: 124
Run Code Online (Sandbox Code Playgroud)

更新2

这是我从PostgreSQL获取结果集的代码:

string sql = "select count(*) from communicationoutgoingmessagescheduledetails " +
                        "where email='" + email + "' ";

        if (message != string.Empty)
            sql += String.Format("and message='{0}' ", message);

        if (subject != string.Empty)
            sql += String.Format("and subject='{0}' ", subject);

        sql += "and successful=true " +
        "and senttime::timestamp::date='" + date.Date + "'";


        System.Data.IDbConnection connection = ORGen.Access.Config.Instance.Connection;
        IDbCommand command = connection.CreateCommand();

        connection.Open();
        command.CommandText = sql;
        bool retVal = Convert.ToInt16(command.ExecuteScalar()) > 0 ? true : false;
        connection.Close();

        command = null;
        connection = null;
Run Code Online (Sandbox Code Playgroud)

Cra*_*ger 20

在PostgreSQL 9.3或更新版本上并且没有手动更改standard_conforming_strings设置,除了单引号之外你不必转义任何东西,你可以像这样加倍:

'this is a single quote: ''. '
Run Code Online (Sandbox Code Playgroud)

如果您使用的是旧版本,请设置standard_conforming_stringsonin postgresql.conf或双反斜杠并使用E''字符串表示法:

E'{\\rtf1'
Run Code Online (Sandbox Code Playgroud)

这一切都在用户手册的词汇结构部分进行了解释.

但是,您应该使用语言的PostgreSQL客户端驱动程序来发送自动转义的参数化语句.如果不这样做会导致SQL注入漏洞 - 请参阅此站点.

由于您使用的是带有npgsql的C#,您可能需要http://bobby-tables.com/csharp.html.npgsql用户手册中给出了更多详细信息.

  • 如果使用美元报价,就像在'$$这是一个单引号:'.$$'时,无需在现代Postgresql中转义单引号 (3认同)