PostgreSQL,Npgsql 返回 42601:“$1”处或附近的语法错误

Tyl*_*ngs 5 postgresql npgsql dapper

我正在尝试使用 Npgsql 和/或 Dapper 来查询表,但我一直遇到 Npgsql.PostgresException 42601: syntax error at or near "$1".

这是我使用 NpgsqlCommand 进行的尝试:

  using (var conn = new NpgsqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["postgres"].ConnectionString))
  {
    conn.Open();
    using (NpgsqlCommand command = new NpgsqlCommand("select * from Logs.Logs where Log_Date > current_date - interval @days day;", conn))
    {
      command.Parameters.AddWithValue("@days", days);
      var reader = command.ExecuteReader();
Run Code Online (Sandbox Code Playgroud)

我也用 Dapper(我的首选方法)尝试过:

  using (var conn = new NpgsqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["postgres"].ConnectionString))
  {
    conn.Open();
    var logs = conn.Query<Log>("select * from Logs.Logs where Log_Date > current_date - interval @days day;", new {days = days});
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,我都会得到相同Npgsql.PostgresException 42601: syntax error at or near "$1" error. 的异常中的语句显示:select * from Logs.Logs where Log_Date > current_date - interval $1 day

请注意,如果我执行以下操作,它可以正常工作,但未正确参数化:

var logs = conn.Query<Log>("select * from Logs.Logs where Log_Date > current_date - interval '" + days + "' day;");
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我非常感谢任何反馈。谢谢你。

aha*_*fox 5

我使用 DapperExtensions 时遇到此错误

添加

DapperExtensions.DapperExtensions.SqlDialect = new PostgreSqlDialect();
DapperAsyncExtensions.SqlDialect = new PostgreSqlDialect();
Run Code Online (Sandbox Code Playgroud)

在创建连接之前修复了问题


Sha*_*sky 4

PostgreSQL 不允许您将参数粘贴在查询中的任何位置。您想要的可以通过以下方式实现:

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

这样,您可以将间隔直接从 Npgsql 传递到 PostgreSQL,而不是设计用于创建该间隔的表达式的一部分。