like statement for npgsql using parameter

穿精又带淫゛_ 提交于 2019-12-03 17:47:58

问题


I have a postgresql DB and i want to query the table "Locations" to retrieve the names of all the locations that match the name that's entered by the user. The column name is "LocationName". I'm using ASP.net with 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();

I get this exception:

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

I've tried running the query without using %, but it doesn't work. I've also tried using + and & like given below but that didn't work either:

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

with the above line, i get this exception:

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

回答1:


you should use

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

you were inserting too much quotes: Postgre interpretes the string between double quote as a field/table-name. Let the parameter do the escape-string job

P.S.: To concatenate string in Postgre you should use the || operator, see here. So your last query should be

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


来源:https://stackoverflow.com/questions/13950279/like-statement-for-npgsql-using-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!