如何使用 C# 中的数据读取器循环遍历行? [英] How do I loop through rows with a data reader in C#?

查看:21
本文介绍了如何使用 C# 中的数据读取器循环遍历行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用 while(dr.Read()){...} 但这会循环我表中的每个字段,我想从第一行检索所有值,并且然后第二个......依此类推.

假设我有一张这样的桌子:

ID--------------Value1--------------Value2-----------------值31你好你好2你好32 嗨1 嗨2 嗨3

首先我要获取hellohello2hello3,然后转到第二行并获取所有值.

有没有办法做到这一点?我希望有人明白我的意思.

非常抱歉,现在已经解决了.我只是没有正确编码...

是的,SqlDataReader.Read() 方法完成了它应该做的事情,同样是我的错误.

解决方案

这就是 DataReader 的工作方式,它旨在一次读取一个数据库行.

while(reader.Read()){var value1 = reader.GetValue(0);//第一次迭代将是 hellovar value2 = reader.GetValue(1);//第一次迭代将是 hello2var value3 = reader.GetValue(2);//第一次迭代将是 hello3}

I know I can use while(dr.Read()){...} but that loops every field on my table, I want to retrieve all the values from the first row, and then second... and so on.

Let's say I have a table like this:

ID--------------Value1--------------Value2------------------Value3
1               hello               hello2                  hello3
2               hi1                  hi2                      hi3

first I want to get, hello, hello2 and hello3 and then go to the second row and get all the values.

Is there a way to achieve this? I hope somebody understand what I mean.

I am so sorry, this is solved now. I just wasn't coding right...

And yeah the SqlDataReader.Read() method does what it is supposed to do, again the mistake was mine.

解决方案

That's the way the DataReader works, it's designed to read the database rows one at a time.

while(reader.Read()) 
{
  var value1 = reader.GetValue(0); // On first iteration will be hello
  var value2 = reader.GetValue(1); // On first iteration will be hello2
  var value3 = reader.GetValue(2); // On first iteration will be hello3
}

这篇关于如何使用 C# 中的数据读取器循环遍历行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆