C# 如何基于组合框选择编写单个sql查询?
我有一个winform,其中用户通过组合框输入值。我正在为搜索数据库分配combobox值。如果没有选择,则SQL server查询不应使用该列进行筛选 范例-C# 如何基于组合框选择编写单个sql查询?,c#,sql,.net,sql-server,C#,Sql,.net,Sql Server,我有一个winform,其中用户通过组合框输入值。我正在为搜索数据库分配combobox值。如果没有选择,则SQL server查询不应使用该列进行筛选 范例- if (string.IsNullOrEmpty(combobox1.text)) { .....Select * from country } else if (combobox1.selectedindex > -1) { ....Select * from country where city_name = com
if (string.IsNullOrEmpty(combobox1.text)) {
.....Select * from country
}
else if (combobox1.selectedindex > -1) {
....Select * from country where city_name = combobox.text
}
如果用户从combobox中选择或不选择值,有没有一种方法可以编写一个查询,而不是使用此多个“如果”条件。如果只有两个条件,则可以使用简写:
string query = string.Format("Select * from country{0}", string.IsNullOrEmpty(combobox1.text) ? "" : " where city_name = " + combobox1.text);
希望有帮助 我认为您必须尝试以下参数化方法:
StringBuilder queryBuilder = new StringBuilder("Select * from country Where 1=1 ");
SqlCommand cmdSql = new SqlCommand();
if (combobox1.selectedindex > -1)
{
queryBuilder.Append(" And city_name = @city_name ");
cmdSql.Parameters.Add("@city_name", SqlDbType.VarChar).Value = combobox.text;
}
else if(Condition 2)
{
queryBuilder.Append(" And column2 = @col2 ");
cmdSql.Parameters.Add("@col2", SqlDbType.VarChar).Value = "some Value here;
}
// Build the query like this
cmdSql.CommandText= = queryBuilder.ToString();
cmdSql.Connection = conObject;
// Here you can execute the command
参数化也很重要:
private const string _select = "select * from country";
void DoSomething()
{
string sql = string.Empty;
if (combobox1.SelectedIndex > -1)
{
command.Parameters.AddWithValue("@1", (string)combobox1.SelectedValue);
sql = " where city_name = @1";
}
sql = _select + sql;
command.CommandText = sql;
command.Execute...
}
@un lucky问我如何应对许多情况——这里有一种方法
var conditions = new List<string>();
if (/* condition 1*/)
{
command.Parameters.AddWithValue("@2", (string)cboN.SelectedItem);
conditions.Add("col1 = @2");
}
if (/* condition 2*/)
{
command.Parameters.AddWithValue("@3", textBoxN.Text);
conditions.Add("col2 = @3");
}
if (conditions.Count > 0)
sql = _select + " where " + string.Join(" AND ", conditions.ToArray());
我有样品,试试看
string select = this.combobox1.GetItemText(this.combobox1.SelectedItem); cm1 = new SqlCommand("Select * from country where city_name=@select or @select is null", con);
cm1.Parameters.Add("@select", SqlDbType.NVarChar, 50);
cm1.Parameters["@select"].Value = select;
dap = new SqlDataAdapter(cm1);
ds = new System.Data.DataSet();
dap.Fill(ds, "DATABASE");
//DataGridView1.DataSource = ds.Tables[0]; get data
如果你没有更多的条件会发生什么?@unlucky,那么这是另一个问题。有很多方法可以解决这个问题。一-将每个条件构建到字段=@参数并添加到列表中。检查列表是否包含任何项,然后使用和作为分隔符添加位置并加入列表项。这是一个solution@un-实际上很幸运,不过技术有点不同。现在看起来很好。。!其中城市名称=+combobox1.text