c# - 从 SqlDataReader 填充通用列表
如何将 SqlDataReader
返回的值添加到通用列表中?我有一种方法,使用 SqlDataReader
从 Category
表中获取 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;
How can I add values that a SqlDataReader
returns to a generic List? I have a method where I use SqlDataReader
to get CategoryID
from a Category
table. I would like to add all the CategoryID
a generic List.
This dose not work because it returns only one categoryID
and that is the last one. I want to add all the categoryID
to the list and then return them.
How do I do that?
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试这样,它更好,更安全,使用延迟加载,更少的代码,工作,...:
然后:
Try like this, it's better, safer, uses lazy loading, less code, working, ...:
and then:
您当前的代码应该可以工作,假设
catID
确实在 try 块之前声明,否则将无法编译。Your current code should work, assuming
catID
is really declared before the try block, otherwise this won't compile.AS BrokenGlass 解释说这是演示
,您将声明更改
为
AS BrokenGlass explained this is the demonstration
as well as you change the declaration
to
这应该可行,但我建议您将
using
与您的connections
一起使用This should work but I suggest you to use
using
with yourconnections