如何使用C#将多个搜索条件包含到SQL命令中

时间:2018-06-17 06:37:19

标签: c# mysql sql

搜索条件来自一个由数据库值[1,2,3,4,5,6 ...]填充的CheckBox-List。

我希望能够检索所选的复选框值,并在执行之前将其包含在SQL命令的WHERE条件中。

Click to see image

    protected void Button1_Click(object sender, EventArgs e)
    {
        string checkedSkills = "";

        //Store The checked values from chkBoxSkillset into a List.
        List<ListItem> selected = new List<ListItem>();
        foreach (ListItem item in chkBoxSkillset.Items)
            if (item.Selected)
                selected.Add(item);

        string checkedSkills = "SELECT DISTINCT Student.*FROM Student" +
            " INNER JOIN StudentSkillSet ON Student.StudentID = 
           StudentSkillSet.StudentID WHERE StudentSkillSet.SkillSetID IN (" 
           + checkedSkills; 

        foreach (ListItem skill in selected)
        {   
            checkedSkills+=Convert.ToString
            (selected[Convert.ToInt16(skill)] + ",");
        }

        checkedSkills += ")";

    }

我使用cmd.Parameters还是QueryString?我应该如何格式化以使其有效?

1 个答案:

答案 0 :(得分:0)

我建议你使用String.Format()String.Join(),例如你可以用这种方式写下你的查询

string query = SELECT DISTINCT Student.* FROM Student 
INNER JOIN StudentSkillSet ON Student.StudentID = 
StudentSkillSet.StudentID WHERE StudentSkillSet.SkillSetID IN ({0})

然后,因为你得到List<ListItem>,你可以使用LINQ获得所需的值,在你的情况下

  

String.Join(", ", select.Select(item => item).Where(x => x.Selected == true).ToList())将以这种方式连接列表中的所有值“item1,item2,item3 ...”

然后,您可以使用自动创建查询的String.Format(query, String.Join(", ", select.Select(item => item).Where(x =>x.Selected == true).ToList()),它比创建多个foreach循环更简洁,更少步骤。