我有一个winform,其中用户通过组合框输入值。我正在为搜索db分配组合框值。如果没有选择,那么SQL服务器查询不应该使用该列进行过滤。
示例 -
if (string.IsNullOrEmpty(combobox1.text)) {
.....Select * from country
}
else if (combobox1.selectedindex > -1) {
....Select * from country where city_name = combobox.text
}
有没有办法编写单个查询,而不是使用此多个' IF'用户选择或不从组合框中选择值的情况。
答案 0 :(得分:3)
同样重要的是参数化:
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());
答案 1 :(得分:0)
如果您有两个条件,则可以使用速记:
string query = string.Format("Select * from country{0}", string.IsNullOrEmpty(combobox1.text) ? "" : " where city_name = " + combobox1.text);
希望它有所帮助!
答案 2 :(得分:0)
我认为你必须尝试使用参数化:
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
答案 3 :(得分:-1)
我有一个样本,试试吧
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