我正在使用SqlDataReader
从存储过程中获取数据。即使获取记录,while (reader.Read())
仅执行一次,因此在我的列表中仅添加了一行。
List<Student> tablelist = new List<Student>();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SP_ReadPromotedStudents"))
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = Data[0];
cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = Data[1];
cmd.Parameters.Add("@Class", SqlDbType.VarChar).Value = Data[2];
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.HasRows)
{
while (reader.Read())
{
tablelist.Add(new Student
{
Name = (string)(reader[0]),
Email = (string)(reader[1]),
Class = (string)(reader[2]),
});
reader.NextResult();
}
}
}
}
}
return tablelist;
我的Student
类:
public class Student
{
public string Name { get; set; }
public string Email { get; set; }
public string Class { get; set; }
}
我有大约46条记录正在获取。但是在列表中仅添加了一条记录。这是什么错误?
您需要将呼叫移至NextResult
循环之外的reader.Read()
。否则,在第一次读取后,代码会遇到NextResult
调用,并尝试加载存储过程返回的第二组数据。
也HasRows
上的循环是一个无限循环。如果属性reader.HasRows
为true,则在您完成读取行后也将为true。
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
tablelist.Add(new Student
{
Name = (string)(reader[0]),
Email = (string)(reader[1]),
Class = (string)(reader[2]),
});
}
// This should be called only if your stored procedure returns
// two or more sets of data otherwise you can remove everything
reader.NextResult();
// If there is another set of data then you can read it with a
// second while loop with
while(reader.Read())
{
.....
}
}
理想的情况是有一个新的sql语句来获取所需的内容,而不是获取列表,只需要第一次访问。想象一下,如果您有一个包含数百万条记录的表,是否需要执行查询才能全部获取并仅读取第一个?不,您可以执行查询来获取所需的内容。
NextResult
中的DataReader
方法将指针移至下一个结果(如果您将其放在结果上)。删除它。
更改sql语句以获取所需的内容后,将循环结果集。您可以只读取第一行(将while
更改为if
):
if (reader.Read())
{
tablelist.Add(new Student
{
Name = (string)(reader[0]),
Email = (string)(reader[1]),
Class = (string)(reader[2]),
});
}