PostgresException:42601:“00”处或附近的语法错误

PostgresException: 42601: syntax error at or near "00"

我正在处理 ASP.NET CORE MVC 项目

我需要从前端传递两个日期,如下所示:HERE

我的看法:

    <form method="post" asp-controller="HOME" asp-action="AllTransactionsList">
    <label> Start Date</label>
    <input type="date"  name="startDate"></br>
    <label> End Date</label>
    <input type="date"  name="endDate"></br>
    <button type="submit">ADD</button>
</form>

我的控制器方法:

        public IActionResult AllTransactionsList(DateTime startDate, DateTime endDate)
    {
        var dataset = new DataSet();
        using var connection = new NpgsqlConnection(connString);
        connection.Open();
        Console.WriteLine(startDate);
        var query = String.Format(@"SELECT accounts.account,accounts.type,DATE(transactions.date),transactions.amount,transactions.note FROM transactions FULL JOIN accounts ON transactions.accountid=accounts.accountid WHERE transactions.date BETWEEN {0} AND {1};", startDate, endDate);

        using (var command = new NpgsqlCommand(query, connection))
        {

            var adapter = new NpgsqlDataAdapter(command);
            adapter.Fill(dataset);
        }

        return View(dataset);

    }

但是在执行 webapp 时,我收到“PostgresException: 42601: syntax error at or near "00"”错误。

我知道将两个日期作为参数传递有问题。谁能帮帮我?

您不应该像这样在查询字符串中直接传递参数:

var query = String.Format(@"SELECT ... BETWEEN {0} AND {1};", startDate, endDate);

首先,像这样将参数合并到查询字符串中可能会产生语法错误(如您所见),除非它本身有效 SQL。

其次,更重要的是,这将导致 SQL 注入漏洞(即使您在 '{0}' 周围加上引号)

相反,您应该 pass parameters with placeholders。这是文档中的示例:

using (var cmd = new NpgsqlCommand("INSERT INTO table (col1) VALUES (@p)", conn)) {
    cmd.Parameters.AddWithValue("p", "some_value");
    cmd.ExecuteNonQuery();
}