【问题标题】:creating sql queries from string array从字符串数组创建 sql 查询
【发布时间】:2018-11-09 18:47:24
【问题描述】:

我的界面-

我正在尝试扩展我的嵌套子查询-

select * from jobs where (location='delhi' or location='Mumbai') and profile in(select profile from jobs where profile='CompScience');

我想在每个选中的复选框的位置将其添加到条件中。 例如,如果勾选的框是德里、孟买、CompScience

查询将是-

select * from jobs where (location='delhi' or location='Mumbai') and profile in(select profile from jobs where profile='CompScience'); 

这是我的尝试-

private void button1_Click(object sender, EventArgs e)
{
    String location=null;
    string profile-null;

    if (checkBox1.Checked == true)
    {
        location+= checkBox1.Text;
    }

    if (checkBox2.Checked == true)
    {
        location += checkBox2.Text;
    }

    if (checkBox3.Checked == true)
    {
        location += checkBox3.Text;
    }

    if (checkBox4.Checked == true)
    {
        profile += checkBox4.Text;
    }

    if (checkBox5.Checked == true)
    {
        profile += checkBox5.Text;
    }

    if (checkBox6.Checked == true)
    {
        profile += checkBox6.Text;
    }

    //MessageBox.Show(location);

    db_CONNECT();
    conn.Open();

    try
    {
        String query = "select * from jobs where(location= 'delhi' or location = 'Mumbai') and profile in(select profile from jobs where profile = 'CompScience');";
        OracleCommand comm2 = new OracleCommand(selectquery, conn);
        OracleDataAdapter MyAdapter = new OracleDataAdapter();//adapter acts as interface btw database and dataset(which is collectio of tables)
        MyAdapter.SelectCommand = comm2;
        DataTable dTable = new DataTable();//datatable represents a single table in database 
        MyAdapter.Fill(dTable);
        dataGridView1.DataSource = dTable;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    conn.Close();
}

我尝试连接字符串,然后从中取出单个元素。

编辑-

private void button1_Click(object sender, EventArgs e)
{
    db_CONNECT();

    try
    {
        CheckBox[] Locations = { checkBox1, checkBox2, checkBox3 };
        CheckBox[] Profiles = { checkBox4, checkBox5, checkBox6 };

        string locs = string.Join(" or ", Locations.Where(c => c.Checked).Select(x => $"location = '{x.Text}'"));
        string profs = string.Join(" or ", Profiles.Where(c => c.Checked).Select(x => $"profile = '{x.Text}'"));
        string query = $"select * from jobs where ({locs}) and profile in(select profile from jobs where {profs})";

        OracleCommand comm2 = new OracleCommand(query, conn);
        OracleDataAdapter MyAdapter = new OracleDataAdapter();//adapter acts as interface btw database and dataset(which is collectio of tables)
        MyAdapter.SelectCommand = comm2;
        DataTable dTable = new DataTable();//datatable represents a single table in database 
        MyAdapter.Fill(dTable);
        dataGridView1.DataSource = dTable;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    conn.Close();
}

【问题讨论】:

标签: c# oracle oracle11g


【解决方案1】:

您可能有一个复选框数组,并使用string.Join() 加入选中的文本:

CheckBox[] Locations = {Checkbox1, CheckBox2, CheckBox3};
CheckBox[] Profiles = {Checkbox4, CheckBox5, CheckBox6};

string locs = string.Join(" or ", Locations.Where(c => c.Checked).Select(x => $"location = '{x.Text}'");
 string profs = string.Join(" or ", Profiles.Where(c => c.Checked).Select(x => $"profile = '{x.Text}'");
string result = $"select * from jobs where ({locs}) and profile in(select profile from jobs where {profs})";

如果您在父容器(如组框或面板)上有复选框,您甚至可以这样做:

CheckBox[] Locations = locPanel.Controls.OfType<CheckBox>().ToArray();
CheckBox[] Profiles = profPanel.Controls.OfType<CheckBox>().ToArray();

【讨论】:

  • 我得到了空元组..我在编辑中附加了我正在使用的代码...也许我在那里做错了什么?
  • @ubuntu_noob 你的复选框数组是空的吗?
  • 我在 GUI 中检查它们
  • @ubuntu_noob 我创建了相同的环境和相同的代码并为我工作。单击按钮时是否选中了复选框?
  • 你能再解释一下代码吗?我没完全看懂
【解决方案2】:
List<string> locations = new List<string>();

我会改变button1_Click方法如下:

private void button1_Click(object sender, EventArgs e)
{       
    if (checkBox1.Checked == true)
    {
        locations.Add(checkBox1.Text);
    }
    else
    {
        locations.Remove(checkBox1.Text);
    }
    // and so on for other locations
}

然后您可以通过以下方式创建查询命令(这只是locations 的示例,对于profile 你应该这样做):

var locationsString = string.Join(", ", locations.Select(l => $"'{l}'"));  // this gives you, e.x. 'Delhi', 'Mumbai'

var query = "";
if (locations.Any())
{
    query = $"select * from jobs where(location in {locationsString }) and profile in(select profile from jobs where profile = 'CompScience');";
}
else
{
    query = $"select * from jobs where profile in(select profile from jobs where profile = 'CompScience');";
}

【讨论】:

    【解决方案3】:

    扩展 Dmitry 的答案,我建议将其进一步简化为

    // ... do locations AND profiles the way Dmitry suggested
    
    // start out with a generic query
    StringBuilder querybuilder = new StringBuilder("SELECT * FROM jobs WHERE 1 = 1");
    
    if (locations.Any())
    {
        var locationsString = string.Join(", ", locations.Select(l => $"'{l}'"));
        querybuilder.AppendFormat(" AND location IN ({0})", locationsString);
    }
    
    if (profiles.Any())
    {
        var profilesString = string.Join(", ", profiles.Select(l => $"'{l}'"));
        querybuilder.AppendFormat(" AND profile IN ({0})", profilesString);
    }
    
    // ...
    
    OracleCommand comm2 = new OracleCommand(querybuilder.ToString(), conn);
    

    包罗万象的WHERE 1 = 1 是创建动态组合查询的普遍接受的方式,可让您大大简化将可变子句附加到查询的条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多