如何使用 executeReader() 方法仅检索一个单元格的值

How to use executeReader() method to retrieve the value of just one cell(如何使用 executeReader() 方法仅检索一个单元格的值)
本文介绍了如何使用 executeReader() 方法仅检索一个单元格的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行以下命令并将结果传递给标签.我不知道如何使用 Reader 来做到这一点.有人可以帮帮我吗?

I need to execute the following command and pass the result to a label. I don't know how can i do it using Reader. Someone can give me a hand?

String sql = "SELECT * FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteReader();

如您所见,我创建了 SQL 语句并执行了它,但它不起作用.为什么?

As you can see i create the SQL statement and i execute it, but it does not work. Why?

控制台说:

不能隐式 SqlDataReader 到字符串...

Cannot implicitly SqlDataReader to String...

我怎样才能得到想要的结果作为字符串,以便标签可以正确显示它.

How can i get the desired results as String so the label can display it properly.

推荐答案

不建议使用DataReaderCommand.ExecuteReader只获取一个 来自数据库的值.相反,您应该使用 Command.ExecuteScalar 如下:

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

<小时>

这里是有关连接到数据库和管理数据的更多信息.


Here is more information about Connecting to database and managing data.

这篇关于如何使用 executeReader() 方法仅检索一个单元格的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)