Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.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
C# 如何在SQL Server中对两个值进行搜索查询_C#_Sql_Sql Server - Fatal编程技术网

C# 如何在SQL Server中对两个值进行搜索查询

C# 如何在SQL Server中对两个值进行搜索查询,c#,sql,sql-server,C#,Sql,Sql Server,我制作了一个C#表单来搜索一个表中的两个值。我的表名为customers,带有字符串ID和字符串cust\u name 我需要进行搜索查询,查找在ID或cust\u name中找到的文本框文本,因此我在textChanged发送此方法时进行了此SQL查询 search(txt_search.Text); SqlDataAdapter searchAdapter; private void search(string id) { searchAdapter = new SqlDataAd

我制作了一个C#表单来搜索一个表中的两个值。我的表名为
customers
,带有字符串
ID
和字符串
cust\u name

我需要进行搜索查询,查找在
ID
cust\u name
中找到的文本框文本,因此我在textChanged发送此方法时进行了此SQL查询

search(txt_search.Text);
SqlDataAdapter searchAdapter;

private void search(string id)
{
    searchAdapter = new SqlDataAdapter(@"Select * from Customers 
       where cust_ID like '%' '" + id + "' '%' or 
             cust_name like '%' '" + id + "' '%'", User.connection);
}

请帮助我纠正错误。

像往常一样,使用参数化查询。错误在于生成查询的字符串部分的串联。有些事情不应该是这样,这是一种常见的情况。在您的特殊情况下,有些空格会弄乱语法。无论如何,参数允许更清晰的查询文本,避免Sql注入和解析错误

private void search(string id)
{
    string cmdText = @"Select * 
                       from Customers 
                       where cust_ID like @id or 
                             cust_name like @id";
    searchAdapter = new SqlDataAdapter(cmdText, User.connection);
    searchAdapter.SelectCommand.Parameters.Add("@id", SqlDbType.NVarChar).Value = "%" + id + "%";

    ... remainder of the code that uses the searchAdapter....
}

通常,使用参数化查询。错误在于生成查询的字符串部分的串联。有些事情不应该是这样,这是一种常见的情况。在您的特殊情况下,有些空格会弄乱语法。无论如何,参数允许更清晰的查询文本,避免Sql注入和解析错误

private void search(string id)
{
    string cmdText = @"Select * 
                       from Customers 
                       where cust_ID like @id or 
                             cust_name like @id";
    searchAdapter = new SqlDataAdapter(cmdText, User.connection);
    searchAdapter.SelectCommand.Parameters.Add("@id", SqlDbType.NVarChar).Value = "%" + id + "%";

    ... remainder of the code that uses the searchAdapter....
}

这句话对吗,我的意思是,我可以在sql语句中使用(或)吗,我的意思是我可以在sql语句中使用(或)吗