gpt4 book ai didi

c# - 从 SQL 获取数据并放入列表

转载 作者:太空狗 更新时间:2023-10-29 18:07:26 25 4
gpt4 key购买 nike

我正在从 SQL 获取数据并将其放入列表中。这就是我现在正在尝试的,

public class Fruit //custom list
{
public string aID { get;set; } // can be more then 1
public string bID { get;set; } // only 2 but different aID
public string name { get;set; } // only 1 for selection of aID and bID
}

这就是我从 sql 中获取数据的方式,

var Fruitee = new Fruit();

using (SqlConnection cn = new SqlConnection(CS()))
{
cn.Open();
SqlCommand sqlCommand= new SqlCommand("SELECT * FROM myTable", cn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
Fruitee.add(reader["aID"], reader["bID"],reader["name"]) // ??? not sure what to put here as add is not available
}
cn.Close();
}

表格看起来像这样,

aID, bID, 姓名

**

  • 问题

**

我不知道如何将项目添加到列表,这也是最佳做法吗?

最佳答案

List<Fruit> fruits = new List<Fruit>();

while (reader.Read())
{
Fruit f = new Fruit();
f.aID = (string) reader["aID"];
f.bID = (string) reader["bID"];
f.name = (string) reader["name"];
fruits.Add(f);
}

关于c# - 从 SQL 获取数据并放入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16856687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com