繁体   English   中英

喜欢使用参数的npgsql语句

[英]like statement for npgsql using parameter

我有一个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将双引号之间的字符串解释为字段/表名。 让参数执行转义字符串作业

PS:要在Postgre中连接字符串,你应该使用|| 运营商,请看这里 所以你的最后一个查询应该是

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM