gpt4 book ai didi

PostgreSQL,Npgsql 返回 42601 : syntax error at or near "$1"

转载 作者:行者123 更新时间:2023-11-29 11:33:22 25 4
gpt4 key购买 nike

我正在尝试使用 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();

我也尝试过使用 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});

无论哪种方式,我都得到相同的 Npgsql.PostgresException 42601: syntax error at or near "$1"error. 异常中的语句显示:select * from Logs.Logs where Log_Date >当前日期 - 间隔 $1 天

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

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

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

最佳答案

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

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

这样您就可以将区间直接从 Npgsql 传递到 PostgreSQL,而不是将表达式的一部分传递给创建该区间。

关于PostgreSQL,Npgsql 返回 42601 : syntax error at or near "$1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37752836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com