当没有预先确定行数时,如何使用SqlDataReader从表中提取数据

本文关键字:SqlDataReader 何使用 数据 提取 | 更新日期: 2023-09-27 18:20:11

我有一个应用程序,允许用户对表中存储的40种不同水果类型进行调查。第一个屏幕允许用户从他/她会尝试的水果列表中进行选择。当用户选择他们的水果类型时,我会在表中获得水果的ID以进行SQL比较,并存储他们选择的不同数量的水果类型。

string strFruits = string.Empty;
foreach (System.Web.UI.WebControls.ListItem li in chkFruits.Items)
{
    if (li.Selected == true)
    {
        strFruits += "'" + li.Value + "'" + ",";
        countFruits += 1;
        ActiveCount += 1;
    }
}

我还有一个List对象,一旦我得到ID,我就用它(在读者的帮助下)从数据库中提取水果类型。如何使用List对象和读取器从表中提取未确定的金额。通常情况下,如果我知道我只想拉前三排,我可以做:

SqlCommand cmd3 = new SqlCommand(@"SELECT [ID], [Fruits] from [my_tastyfruits]", conn1);
using (SqlDataReader reader1 = cmd3.ExecuteReader())
{
    while (reader1.Read())
    {
        MyFruits foo = new MyFruits();
        foo.ID = reader1.GetInt32(0);
        foo.Fruits = reader1.GetString(1);
        myFruits.Add(foo);
    }
    //assign fruits here
    strFruit1 = MyFruits[0].Fruits;
    strFruit2 = MyFruits[1].Fruits;
    strFruit3 = MyFruits[2].Fruits;
...
}

然而,由于计数由用户决定,我不确定如何通过读取器提取数据。

当没有预先确定行数时,如何使用SqlDataReader从表中提取数据

将数据保留在(MyFruit集合中,稍后进行适当处理。

例如,根据需要对其进行迭代以进行显示;

foreach (var fruits in MyFruits) {
   Console.WriteLine(fruits.Fruits);
}

在运行时,不能将任意大小的列表分配给任意数量的变量:编译代码时,变量的数量和类型是固定的。