问题
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