How to use executeReader() method to retrieve the value of just one cell
I need to e开发者_JAVA百科xecute 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();
As you can see i create the SQL statement and i execute it, but it does not work. Why?
The console says:
Cannot implicitly SqlDataReader to String...
How can i get the desired results as String so the label can display it properly.
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * FROM learer WHERE id = @id";
cmd.Parameters.AddWithValue("@id", index);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
}
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.
ExecuteScalar()
is what you need here
Duplicate question which basically says use ExecuteScalar()
instead.
精彩评论