c# - like 使用参数的 npgsql 语句

标签 c# asp.net npgsql

我有一个 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

最佳答案

你应该使用

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 || '%'";

关于c# - like 使用参数的 npgsql 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13950279/

相关文章:

c#、Mysql数据比较问题

c# - C# Npgsql 传递的复合类型数组作为存储过程输入

c# - Entity Framework 6 - Npgsql - 连接字符串错误

c# 在保存对话框上自定义控件——如何禁用父文件夹按钮?

.net - 在 ASP.NET 中使用更少的内存

c# - 在 Model asp.net c# 中初始化值

c# - Asp.Net MVC - 使用 Entity Framework + Npgsql.Entityframework 访问 Postgresql

c# - 在 ASP.NET MVC Controller 中进行 setter 注入(inject)时如何传递模拟对象

c# - .Net 阻止 API Web 服务连接

javascript - 如何使用asp.net MVC合并JSON中的两个数组列表并在数据表行中查看?