简体   繁体   English

在单引号中设置参数值的Postgres准备语句错误

[英]Postgres prepared statement error on setting parameter value in single quote

I am using parameterized query to the Postgres database in C#. 我在C#中使用对Postgres数据库的参数化查询。

NpgsqlCommand command = new NpgsqlCommand("(SELECT * " +
    "FROM ABC AS abc " +
    " WHERE abc.SomeDate >= date_trunc('month', current_date) + interval '@periods' ");

command.Parameters.AddWithValue("periods", NpgsqlDbType.Text, periods);

where periods value format = '-5 years' or '-2 years' 其中期间值格式=“-5年”或“ -2年”

On executing error is 在执行错误是

22007: invalid input syntax for type interval: "@periods"

When I remove ' (single quote) from the @periods , It gives the error: 当我从@periods删除'(单引号)时,出现错误:

Error: 42601: syntax error at or near "$2"

Please suggest a way. 请提出一种方法。 Thanks. 谢谢。

You can't use parameter placeholders inside literals this way. 您不能以这种方式在文字中使用参数占位符。 Instead of writing interval '@param' , just write @param : Npgsql transmits the type information to PostgreSQL in the protocol with the parameter. 而不是写interval '@param' ,只需写@param :Npgsql使用协议将类型信息发送到协议中的PostgreSQL。 In some cases you may need to specify NpgsqlDbType on your parameter to tell Npgsql which type to send (but in most cases it is inferred correctly from the CLR type). 在某些情况下,您可能需要在参数上指定NpgsqlDbType来告诉Npgsql发送哪种类型(但在大多数情况下,可以从CLR类型正确推断出)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM