如何添加SqlDataReader
返回到通用列表的值?我有一种方法,我使用SqlDataReader
从CategoryID
表中获取Category
。我想添加所有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;
答案 0 :(得分:15)
尝试这样,它更好,更安全,使用延迟加载,更少代码,工作,......:
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();
答案 1 :(得分:3)
您当前的代码应该有效,假设在try块之前确实声明了catID
,否则这将无法编译。
答案 2 :(得分:1)
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
答案 3 :(得分:0)
这应该可以,但我建议您将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;
答案 4 :(得分:0)
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();