gpt4 book ai didi

c# - SqlCommand 只返回一行

转载 作者:行者123 更新时间:2023-11-30 19:24:16 25 4
gpt4 key购买 nike

试图只返回前几行,因为我的数据库太大了,但是当我测试我的 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();

我的解决方案有什么问题?

最佳答案

在你的循环中,你不断地重新创建变量的实例 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);
}

您可以将此列表用作网格的数据源,或者只保留它以备将来引用...

    foreach(Log log in logs)
MessageBox.Show(log.Id);

关于c# - SqlCommand 只返回一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38883567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com