【问题标题】:c# - Fill generic list from SqlDataReaderc# - 从 SqlDataReader 填充通用列表
【发布时间】:2011-08-02 13:28:07
【问题描述】:

如何将SqlDataReader 返回的值添加到通用列表?我有一种方法,我使用SqlDataReaderCategory 表中获取CategoryID。我想将所有CategoryID 添加一个通用列表。

这不起作用,因为它只返回一个categoryID,这是最后一个。我想将所有categoryID 添加到列表中,然后返回它们。

我该怎么做?

SqlConnection connection = null;
SqlDataReader reader = null;
SqlCommand cmd = null;

try
{
    connection = new SqlConnection(connectionString);
    cmd = new SqlCommand("select CategoryID from Categories", connection );

    connection.Open();

    List<int> catID = new List<int>();
    dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        catID.Add(Convert.ToInt32(dr["CategoryID"].ToString()));
    }
}
finally
{
    if (connection  != null)
        connection.Close();
}
return catID;

【问题讨论】:

  • 你有一个名为catId字段吗?
  • 在连接、命令和阅读器周围使用 using 语句!

标签: c# sql sqldatareader


【解决方案1】:

试试这样,更好,更安全,使用延迟加载,更少代码,工作,...:

public IEnumerable<int> GetIds()
{
    using (var connection = new SqlConnection(connectionString))
    using (var cmd = connection.CreateCommand())
    {
        connection.Open();
        cmd.CommandText = "select CategoryID from Categories";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                yield return reader.GetInt32(reader.GetOrdinal("CategoryID"));
            }
        }
    }
}

然后:

List<int> catIds = GetIds().ToList();

【讨论】:

  • @Darim:虽然我喜欢这段代码,尽管调用ToList() 是消费者的责任 - 否则你有一个开放的数据库连接。我不相信惰性是正确的方法。
  • @BrokenGlass 没有。一旦退出foreach,连接,阅读器,所有这些东西都会关闭。除了这个优点之外,一个缺点是如果您必须重新使用 IEnumerable 中的对象并且您还没有将所有这些对象都存储在某个地方,那么调用者将不得不从数据库中重新读取数据。我的意思是如果你没有完全“foreach”。使用ToList(),您已经在某个地方拥有了它们..
  • GetOrdnal 确实没有必要,尤其是查询是这样的单列时,reader.GetOrdinal("CategoryID") 可以直接替换为0
  • 我们可以为 List 做吗?
【解决方案2】:

假设 catID 确实在 try 块之前声明,您当前的代码应该可以工作,否则将无法编译。

【讨论】:

  • catID 已声明。当我测试我的代码时,我只得到一个 CategoryID 而不是我表中的四个。
  • @Erik:你能用你正在运行的真实代码更新你的示例代码吗,你可能每次都在更新列表,但上面的代码显然不是你目前正在使用什么。
【解决方案3】:

AS BrokenGlass 解释说这是演示

SqlConnection connection = null;
        SqlDataReader dr= null;
        SqlCommand cmd = null;
List<int> catID = new List<int>();
        try
        {
            connection = new SqlConnection(connectionString);
            cmd = new SqlCommand("select CategoryID from Categories", connection );

            connection.Open();



            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                catID.Add(Convert.ToInt32(dr["CategoryID"].ToString()));
            }


        }
        finally
        {
            if (connection  != null)
                connection.Close();
        }
        return catID;

以及您更改声明

SqlDataReader reader = null;

SqlDataReader dr= null; // Because you are using dr in the code not reader

【讨论】:

    【解决方案4】:

    这应该可以,但我建议您将using 与您的connections 一起使用

        SqlConnection connection = null;
        SqlDataReader reader = null;
        SqlCommand cmd = null;
        List<int> catID = new List<int>();
        try
        {
            connection = new SqlConnection(connectionString);
            cmd = new SqlCommand("select CategoryID from Categories", connection );
    
            connection.Open();
    
    
    
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {   
                catID.Add(Convert.ToInt32(dr["CategoryID"].ToString()));
            }
    
    
        }
        finally
        {
            if (connection  != null)
                connection.Close();
        }
        return catID;
    

    【讨论】:

      【解决方案5】:
              List<int> s = new List<int>();
              conn.Open();
              SqlCommand command2 = conn.CreateCommand();
              command2.CommandText = ("select turn from Vehicle where Pagged='YES'");
              command2.CommandType = CommandType.Text;
              SqlDataReader reader4 = command2.ExecuteReader();
              while (reader4.Read())
              {
                  s.Add(Convert.ToInt32((reader4["turn"]).ToString()));
              }
              conn.Close();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多