mim*_*ckd 2 c# sql sql-server sqlcommand
尝试只返回前几行,因为我的数据库太大了,但是当我测试我的SQL时,我做了一个select *并且只返回了第一行.
SqlCommand sqlCmd = new SqlCommand();
SqlDataReader reader;
sqlCmd.CommandText = "SELECT * FROM Log";
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
Log logs = null;
while (reader.Read())
{
logs = new Log();
logs.Id = Convert.ToInt32(reader.GetValue(0));
}
return logs;
myConnection.Close();
Run Code Online (Sandbox Code Playgroud)
我的解决方案有什么问题?
在循环中,您不断重新创建变量的实例,logs从而覆盖前一个变量并以查询返回的最后一个记录的值结束.你需要一个List<Log>
List<Log> logs = new List<Log>();
while (reader.Read())
{
Log current = new Log();
logs.Id = Convert.ToInt32(reader.GetValue(0));
logs.Add(current);
}
Run Code Online (Sandbox Code Playgroud)
您可以将此列表用作网格的数据源,或者将其保留以供将来参考...
foreach(Log log in logs)
MessageBox.Show(log.Id);
Run Code Online (Sandbox Code Playgroud)