Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有搜索变量参数的Npgsql查询返回空结果C#Postgres_C#_Postgresql_Npgsql - Fatal编程技术网

带有搜索变量参数的Npgsql查询返回空结果C#Postgres

带有搜索变量参数的Npgsql查询返回空结果C#Postgres,c#,postgresql,npgsql,C#,Postgresql,Npgsql,我正在使用Npgsql查询数据库表,并在我的页面/视图上显示结果。代码在没有where子句和参数的情况下运行良好,因为它将表中的所有行都放到视图中。现在,我正在尝试合并一个搜索字符串变量(如果用户在字符串中键入,那么给我包含该字符串的表记录)。我的代码如下 string searchValue = TempData["String"].ToString(); var model = new List<ProductViewModel>(); NpgsqlConnect

我正在使用Npgsql查询数据库表,并在我的页面/视图上显示结果。代码在没有where子句和参数的情况下运行良好,因为它将表中的所有行都放到视图中。现在,我正在尝试合并一个搜索字符串变量(如果用户在字符串中键入,那么给我包含该字符串的表记录)。我的代码如下

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);

但是在包含where子句和我的搜索字符串变量之后,我得到了一个空页面。我的代码在这方面做错了什么?

您可能希望在查询中使用
%
来使用运算符

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

searchValue
的内容是什么?还可以查看文档。在调试时,searchValue始终是我在searchbox中键入的任何文本(这是预期的行为)。它只是跳过while循环,在添加where子句时直接转到pagedProduct。我会看一看文档。我之前有一行可能是重复的,结果是完全相同的空结果。缺少的
%
就是我得到的。您可以尝试手动对数据库运行相同的查询,而不需要中间的c层,并检查是否有结果。使用正确的连接更新&auto-parameter quotingthanks for the assist@JGH和0xCAFEBABE。连接修复解决了我的问题,现在我得到了想要的功能。干杯
NpgsqlCommand cmd = new NpgsqlCommand
     ("SELECT * FROM q_product WHERE q_description like '%' || @string || '%'", connection);