Npgsql query with search variable parameter returning empty result C# Postgres

杀马特。学长 韩版系。学妹 提交于 2019-12-25 09:28:34

问题


I am using Npgsql to query a database table and show the results on my page/view. The code works fine WITHOUT the where clause and parameters as it gets all the rows from the table onto the view. Now I am trying to incoporate a search string variable (if the user types in the string, then give me the table records that contain this string). My code is as follows

string searchValue = TempData["String"].ToString();

var model = new List<ProductViewModel>();      

NpgsqlConnection connection = new NpgsqlConnection
     ("Host=192.168.0.52;Database=test;Username=test;Password=test");
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand
     ("SELECT * FROM q_product WHERE q_description like @string", connection);

        //lets include our paramater
cmd.Parameters.Add("@string", NpgsqlTypes.NpgsqlDbType.Text);
cmd.Parameters["@string"].Value = searchValue;
cmd.Parameters.AddWithValue(searchValue);

NpgsqlDataReader dr = cmd.ExecuteReader();

while (dr.Read())
{
    var prod = new ProductViewModel();
    prod.q_description = dr["q_description"].ToString();
    prod.q_barcode = dr["q_barcode"].ToString();               

    model.Add(prod);  
}

var pagedProduct = new PaginatedSearch<ProductViewModel>(model, pageIndex, pageSize);

return View(pagedProduct);

Records are returned fine when I only have

SELECT * FROM q_product

but after including the where clause and my search string variable, I am getting an empty page. What am I doing wrong in my code for this?


回答1:


You probably want to use % in your query to make use of the like operator.

NpgsqlCommand cmd = new NpgsqlCommand
     ("SELECT * FROM q_product WHERE q_description like '%' || @string || '%'", connection);


来源:https://stackoverflow.com/questions/44779362/npgsql-query-with-search-variable-parameter-returning-empty-result-c-sharp-postg

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