How to use executeReader() method to retrieve the value of just one cell(如何使用 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.
推荐答案
不建议使用DataReader和Command.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() 方法仅检索一个单元格的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 executeReader() 方法仅检索一个单元格的值
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
