如何在 C# 中循环 sql 查询

本文关键字:循环 sql 查询 | 更新日期: 2023-09-27 17:55:48

我想执行 10 次查询以获得随机值,但我的代码永远不会停止,
它不断循环并且没有响应。

这是我的代码

int j = 0;
do {
    DataSet AVATARLINE = new DataSet();
    SqlDataAdapter AVATARLINE_1 = new SqlDataAdapter("DECLARE
            @Random INT,@Upper INT,
            @Lower INT SET @Lower = (select MIN(ID)from MastryID)SET
            @Upper = (select MAX(ID)from MastryID)+1 SELECT
            @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)SELECT @Random", connection);
    AVATARLINE_1.Fill(AVATARLINE);
    foreach (DataRow row in AVATARLINE.Tables[0].Rows)
    {
        for (int i = 0; i < AVATARLINE.Tables[0].Columns.Count; i++)
        richTextBox1.Text += row[i].ToString() + Environment.NewLine;
    }
}
while (j < 10); // 0-9

任何知道如何让它只工作 10 次。

如何在 C# 中循环 sql 查询

你去:)...你似乎没有在你的循环中递增j

int j = 0;
    do {
            DataSet AVATARLINE = new DataSet();
            SqlDataAdapter AVATARLINE_1 = new SqlDataAdapter("DECLARE @Random INT,@Upper INT,@Lower INT SET @Lower = (select MIN(ID)from MastryID)SET @Upper = (select MAX(ID)from MastryID)+1 SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)SELECT @Random", connection);
            AVATARLINE_1.Fill(AVATARLINE);
            foreach (DataRow row in AVATARLINE.Tables[0].Rows)
            {
                for (int i = 0; i < AVATARLINE.Tables[0].Columns.Count; i++)
                    richTextBox1.Text += row[i].ToString() + Environment.NewLine;
            } 
        j++; 
        }
    while (j < 10); // 0-9

添加++

int j = 0;
do {
        DataSet AVATARLINE = new DataSet();
        SqlDataAdapter AVATARLINE_1 = new SqlDataAdapter("DECLARE @Random INT,@Upper INT,@Lower INT SET @Lower = (select MIN(ID)from MastryID)SET @Upper = (select MAX(ID)from MastryID)+1 SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)SELECT @Random", connection);
        AVATARLINE_1.Fill(AVATARLINE);
        foreach (DataRow row in AVATARLINE.Tables[0].Rows)
        {
            for (int i = 0; i < AVATARLINE.Tables[0].Columns.Count; i++)
                richTextBox1.Text += row[i].ToString() + Environment.NewLine;
        }  
    }
while (++j < 10); // 0-9

任何其他递增j的方法都可以。 更传统的方法是 for 循环:

for (int j = 0; j < 10; j++)
{
    DataSet AVATARLINE = new DataSet();
    SqlDataAdapter AVATARLINE_1 = new SqlDataAdapter("DECLARE @Random INT,@Upper INT,@Lower INT SET @Lower = (select MIN(ID)from MastryID)SET @Upper = (select MAX(ID)from MastryID)+1 SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)SELECT @Random", connection);
    AVATARLINE_1.Fill(AVATARLINE);
    foreach (DataRow row in AVATARLINE.Tables[0].Rows)
    {
        for (int i = 0; i < AVATARLINE.Tables[0].Columns.Count; i++)
            richTextBox1.Text += row[i].ToString() + Environment.NewLine;
    }  
}

最后,您可能想阅读有关Random类的信息:http://msdn.microsoft.com/en-us/library/system.random.aspx