从字符串数组创建sql查询

时间:2018-11-09 09:43:35

标签: c# oracle oracle11g

我的界面-

enter image description here

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

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();
}

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

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');";
}

答案 2 :(得分:1)

扩展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是创建动态组合查询的常用方法,可让您大大简化将变量子句附加到查询中的条件。