SqlDataReader [0] 为空

发布于 2024-09-29 22:42:30 字数 366 浏览 1 评论 0原文

我想在文本字段中显示 SqlDataReader 的第一行(它是数据库返回的唯一行/列)。我认为这是正确的语法,但我收到“无数据”错误。我可以确保正在使用的 sql 查询肯定会返回答案,我已经在 SQL Server 中检查过它。

SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
Label1.Text = reader[0].ToString();

reader[0] 似乎没有显示任何内容。

I'm wanting to display the first row of a SqlDataReader (its the only row/column the database returns) in a text field. I thought this was the correct syntax but i get 'no data' error. I can ensure that the sql query being used should definitely return an answer, i've checked it in SQL Server.

SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
Label1.Text = reader[0].ToString();

reader[0] doesn't seem to show anything.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

﹎☆浅夏丿初晴 2024-10-06 22:42:31

如果我记得正确的话,您需要实际读取数据:

reader.Read()

您可以迭代或仅使用第一个值。

You need to actually read the data if I remember correctly using:

reader.Read()

Which you can iterate through or just use the first value.

帅哥哥的热头脑 2024-10-06 22:42:31

您需要调用 read() 来移动到行。它通常用作

   while(reader.read())
   {
        // do something
   }

在您的情况下在分配给标签之前放置 reader.read()

*还要记住始终关闭它 - 因此在 using 块中使用它。 *

You need to call read() to move to the rows. It is usually used as

   while(reader.read())
   {
        // do something
   }

In you case put reader.read() before assigning to label.

*Also remember always to close it - so use it in using block. *

盗琴音 2024-10-06 22:42:31

请阅读 DataReader 的文档。索引器提供基于序号/列号的值。由于您尚未开始(或正在)浏览阅读器,因此它将是空的。

Please read the documentation for DataReader. The indexer provides a value based on the ordinal/column number. As you have not started (or are) moving through the reader, it will be empty.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文