0

我想使用每个 listbox1 项目来运行两个查询,如果两个结果不同,则将该项目移动到另一个名为 listbox2 的列表框,如果它们相同,则从 listbox1 中删除该项目。

foreach (string Items in listBox1.Items)
{
    using (OracleCommand crtCommand = new OracleCommand("select count(*) from(( select * from all_ind_columns where  index_name= '" + Items + "'  and table_owner='" + txtSrcUserID.Text.ToUpper() + "'))", conn1))
    using (OracleCommand ctCommand = new OracleCommand("select count(*) from(( select * from all_ind_columns where  index_name= '" + Items + "'  and table_owner='" + txtDesUserID.Text.ToUpper() + "'))", conn1))
    {
        string result1 = crtCommand.ExecuteScalar().ToString();
        string result2 = ctCommand.ExecuteScalar().ToString();

        if (result1 != result2)
        {
            //move that item to listbox2
        }
        else if(result1 == result2)
        {
            // remove that item from listbox1
        }
    }
}
4

1 回答 1

2

您不能foreach在这里使用,因为您更改了listBox1.Items循环内部,使用 while 循环并检查循环listBox1.Items.Count() >0内部的 and 您可以拍摄第一项并将其移动到第二项或删除。

while (ListBox1.Items.Count>0)
{
    var item =  ListBox1.Items[0].ToString();

    using (OracleCommand crtCommand = new OracleCommand("select count(*) from(( select * from all_ind_columns where  index_name= '" + item + "'  and table_owner='" + txtSrcUserID.Text.ToUpper() + "'))", conn1))
    using (OracleCommand ctCommand = new OracleCommand("select count(*) from(( select * from all_ind_columns where  index_name= '" + item + "'  and table_owner='" + txtDesUserID.Text.ToUpper() + "'))", conn1))
    {
        string result1 = crtCommand.ExecuteScalar().ToString();
        string result2 = ctCommand.ExecuteScalar().ToString();
        if (result1 != result2)
        {
            ListBox2.Items.Add(item);
        }
        ListBox1.Items.RemoveAt(0);
    }   

}

注意: 您的代码对 sql 注入攻击是开放的,请使用参数而不是内联参数。

while (ListBox1.Items.Count>0)
{
    var item =  ListBox1.Items[0].ToString();

    using (OracleConnection con = new OracleConnection(connectionString))
    using (OracleCommand cmd = con.CreateCommand())
    {
        con.Open();
        cmd.CommandText = "select count(*) from(( select * from all_ind_columns where  index_name= :item  and table_owner=:table_owner))";
        cmd.Parameters.Add(item);
        cmd.Parameters.Add(txtSrcUserID.Text.ToUpper());

        string result1 = cmd.ExecuteScalar().ToString();
        cmd.Parameters.Clear();
        cmd.Parameters.Add(item);
        cmd.Parameters.Add(txtDesUserID.Text.ToUpper());
        string result2 = cmd.ExecuteScalar().ToString();

        if (result1 != result2)
        {
            ListBox2.Items.Add(item);
        }
        ListBox1.Items.RemoveAt(0);
    }

}
于 2013-07-26T04:09:40.007 回答