PostgreSQL, Npgsql returning 42601: syntax error at or near “$1”

后端 未结 3 1857
醉酒成梦
醉酒成梦 2021-01-13 19:00

I\'m trying to use Npgsql and/or Dapper to query a table and I keep running into Npgsql.PostgresException 42601: syntax error at or near \"$1\".

Here is

相关标签:
3条回答
  • 2021-01-13 19:35

    To subtract days from a date (assuming log_date is data type date), you can simplify:

    "SELECT * FROM logs.logs WHERE log_date > CURRENT_DATE - @days;"
    

    And provide @days as unquoted numeric literal (digits only) - which is taken to be an integer. This is even more efficient, since date - integer returns date, while date - interval returns timestamp.

    The manual about interval input.

    0 讨论(0)
  • 2021-01-13 19:41

    PostgreSQL doesn't allow you to stick a parameter anywhere in a query. What you want can be achieved with the following:

    var command = new NpgsqlCommand("select * from Logs.Logs where Log_Date > current_date - @days", conn))
    command.Parameters.AddWithValue("@days", TimeSpan.FromDays(days));
    

    This way you're passing the interval directly from Npgsql to PostgreSQL, rather than a part of the expression designed to create that interval.

    0 讨论(0)
  • 2021-01-13 19:54

    i got this error using DapperExtensions

    adding

    DapperExtensions.DapperExtensions.SqlDialect = new PostgreSqlDialect();
    DapperAsyncExtensions.SqlDialect = new PostgreSqlDialect();
    

    before creating the connection fixed the issue

    0 讨论(0)
提交回复
热议问题