问题描述
我需要执行以下命令并将结果传递给标签.我不知道如何使用 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() 方法仅检索一个单元格的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!