简体   繁体   English

如何获取 SQL 服务器表来存储列表?

[英]How get SQL Server table to be store a list?

As a java developer, this is possible easily.作为 java 开发人员,这很容易实现。 But I wasn't able to achieve it in C#.但我无法在 C# 中实现它。 I want to get data from the SQL Server database and store them in a list that is of type object to meet the table needs.我想从 SQL 服务器数据库中获取数据,并将它们存储在 object 类型的列表中以满足表需求。

The object: object:

class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}

and the table in the database:和数据库中的表:

在此处输入图像描述

and the code:和代码:

public List<Category> GetCategoryList() 
{
        connect.Open();

        SqlCommand cmd = new SqlCommand("Select * From Category", connect);

        int i = cmd.ExecuteNonQuery();

        connect.Close();
}

I believe there is something named DataReader I got to use it but I couldn't find an explanation or an example of how to use it in such a situation like mine我相信有一个名为DataReader的东西我必须使用它,但我找不到解释或示例说明如何在像我这样的情况下使用它

public List<Category> GetCategoryList() 
{
    List<Category> columnData = new List<Category>();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand cmd = new SqlCommand("Select * From Category", connect);
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(new Category {
                    Id= reader["Id"] is DBNull ? null : int.Parse(reader["Id"]),
                    Name = reader["Name"] is DBNull ? null : reader["Name"].ToString() 
                });
            }         
        }
    }
    return columnData;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM