c# – 类似于使用参数的npgsql语句

前端之家收集整理的这篇文章主要介绍了c# – 类似于使用参数的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

解决方法

@H_301_20@ 你应该使用
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 || '%'";
原文链接:https://www.f2er.com/csharp/101133.html

猜你在找的C#相关文章