使用参数的npgsql的like语句

11

我有一个PostgreSQL数据库,想要查询表"Locations"以检索与用户输入的名称匹配的所有位置名称。 列名为"LocationName"。 我正在使用ASP.net和C#。

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使用运算符||来连接字符串,而不是加号(+)。 - alfoks
1个回答

22

你应该使用

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

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

P.S.:在Postgre中连接字符串应该使用||运算符,可以参考这里。因此,您的最后一个查询应该是:

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

成功了!现在它正在返回所有匹配的行。感谢@trippino的帮助和如此快速的响应。 - NamrataP
1
很高兴能帮到你。欢迎来到 Stack Overflow :) - Tobia Zambon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接