【问题标题】:like statement for npgsql using parameterlike 使用参数的 npgsql 语句
【发布时间】:2012-12-06 16:20:31
【问题描述】:

我有一个 postgresql 数据库,我想查询“位置”表以检索与用户输入的名称匹配的所有位置的名称。列名是“LocationName”。我正在使用带有 C# 的 ASP.net。

NpgsqlConnection con = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString());

NpgsqlCommand cmd = new NpgsqlCommand("Select * from \"Locations\" where \"LocationName\" LIKE \"%@loc_name%\"", con);

cmd.Parameters.AddWithValue("@loc_name", Location_Name);

NpgsqlDataReader reader = cmd.ExecuteReader();

我得到了这个例外:

Npgsql.NpgsqlException: ERROR: 42703: column "%((E'My place'))%" does not exist

我尝试过不使用 % 来运行查询,但它不起作用。 我也尝试过使用 + 和 & 如下所示,但这也不起作用:

string query = "Select \"LocationName\" from \"Locations\" where \"LocationName\" LIKE '%'+ :loc_name +'%'";

通过上面的行,我得到了这个异常:

Npgsql.NpgsqlException: ERROR: 42725: operator is not unique: unknown + unknown

【问题讨论】:

  • 最后一个查询:postgres 正在使用运算符 ||用于连接字符串,而不是加号 (+)。

标签: c# asp.net npgsql


【解决方案1】:

你应该使用

NpgsqlCommand cmd = new NpgsqlCommand("Select * from \"Locations\" where \"LocationName\" LIKE @loc_name", con);
cmd.Parameters.AddWithValue("@loc_name", "%" + Location_Name + "%");

您插入了太多引号:Postgre 将双引号之间的字符串解释为字段/表名。让参数做转义字符串工作

P.S.:要在 Postgre 中连接字符串,您应该使用 || 运算符,请参阅 here。所以你的最后一个查询应该是

string query = "Select \"LocationName\" from \"Locations\" where \"LocationName\" LIKE '%' || :loc_name || '%'";

【讨论】:

  • 成功了!!现在它返回所有匹配的行。感谢@trippino 的帮助和如此快速的回复。
  • 很高兴为您提供帮助。欢迎堆栈溢出:)
猜你喜欢
  • 1970-01-01
  • 2015-06-03
  • 1970-01-01
  • 2015-12-03
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
相关资源
最近更新 更多