【问题标题】:Sql query does not bring more than 4 results in a for loop in C#Sql 查询在 C# 中的 for 循环中不会带来超过 4 个结果
【发布时间】:2013-07-18 16:58:07
【问题描述】:

这段代码只能从 0 循环到 3。当我将变量 i 增加到 4 或更多时,它不会带来结果。我有将近 700 条描述要查询。我怎样才能做到这一点?这是我的代码。谢谢,

SqlCommandBuilder myBuilder;
DataSet mySet;
DataTable myTable;
SqlDataReader myReader = null;
SqlCommand myCommand = null;

private void button1_Click(object sender, EventArgs e)
{
    String str = "";
    int specRowCount = dataGridView2.Rows.Count;

    mySet = new DataSet();

    try
    {
        myConnection.Open();
        for (int i = 0; i <= 3; i++)
        {
           str = "use " + textBox4.Text + " SELECT * FROM myTable where myRule=1 and myFlag=1 and description='" + dataGridView2.Rows[i].Cells[0].Value.ToString() + "'";
            //myCommand = new SqlCommand(str, myConnection);
            myAdapter = new SqlDataAdapter(str, myConnection);
            //myBuilder = new SqlCommandBuilder(myAdapter);

            myAdapter.Fill(mySet, "t_rules");  
        }
        myTable = mySet.Tables["t_rules"];
        myConnection.Close();

        dataGridView1.DataSource = mySet.Tables["t_rules"];

        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }  
}

【问题讨论】:

  • 您的代码容易受到 SQL 注入攻击,我会先解决这个问题。
  • 附带说明,这显然不是控制台应用程序,但问题是写入控制台。
  • 1) 为循环设置固定大小不是一个好主意。它应该基于网格行(如果你坚持这条路线)。 2) 如果您的任何 [Description] 值包含撇号 ('),您将收到错误消息。 3)通过循环的每次迭代,当您调用 myAdapter.Fill(mySet, "t_rules") 时,您将覆盖您的数据集。所以在一个循环中重新查询会打败你的数据库。您应该只运行最后一个查询,因为这是您要保留的唯一结果集。

标签: c# sql data-binding datagridview connection


【解决方案1】:

此代码在增加计数器时无法返回更多结果的唯一方法是让SELECT 语句返回零行。由于某种原因,该查询正在排除您正在查询的其他行。

将计数器增加到 700,您可能会或可能不会获得更多数据,这取决于此查询返回的内容。

但在一天结束时,查询返回零行。

【讨论】:

    【解决方案2】:

    @Grant Thomas 和@Paulie Waulie 是对的。问题是(可能)因为您在 dataGridView2 第 3 行的 [description] 中有一个撇号。它抛出一个错误,你正在捕捉它却没有看到它。尝试在你的 catch 块中放置一个消息框或断点,你会看到。

    要修复您的查询,请尝试以下操作:

    str = "use " + textBox4.Text + "; SELECT * FROM myTable 
    where myRule=1 and myFlag=1 and [description]='" + 
    Replace(dataGridView2.Rows[i].Cells[0].Value.ToString(),"'","''") + "'";
    

    【讨论】:

    • 谢谢你们!撇号问题!!!下面的代码解决了!谢谢你,戈利什! cleanDesc =dataGridView2.Rows[i].Cells[0].Value.ToString().Replace("'","''");str = "use " + textBox4.Text + " SELECT * FROM t_rules whereruletype=1 and currentflag=1 and description='" + cleanDesc + "'";
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多