33

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();

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
javing
  • 12,307
  • 35
  • 138
  • 211

4 Answers4

50
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"))
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • "reader.GetString(reader.GetOrdinal("somecolumn"))" is the easiest way to retrieve a text value ? there's nothing like reader.fieldByName("Name").asString ? – Rebelss Jan 24 '14 at 22:25
  • 3
    Thank you for showing me how to use `ExecuteReader()` and not Scalar as the question asked – AlbatrossCafe Nov 06 '15 at 22:19
  • side note you cannot do this with table names just the variables – Robot70 Jun 21 '17 at 20:51
29

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.

Mukus
  • 4,870
  • 2
  • 43
  • 56
Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
  • `"SELECT ColumnNumber FROM learer WHERE learer.id = " + index` may have a [SQL injection attack](https://en.wikipedia.org/wiki/SQL_injection) vulnerability. Instead use a parameterized query as shown in e.g. [this answer](https://stackoverflow.com/a/5794580/3744182/3744182). See: [Why do we always prefer using parameters in SQL statements?](https://stackoverflow.com/q/7505808/3744182) and also https://software-security.sans.org/developer-how-to/fix-sql-injection-microsoft-.net-with-parameterized-queries – dbc Jan 17 '20 at 21:46
2

ExecuteScalar() is what you need here

iTSrAVIE
  • 846
  • 3
  • 12
  • 26
0

Duplicate question which basically says use ExecuteScalar() instead.

Community
  • 1
  • 1
m.edmondson
  • 30,382
  • 27
  • 123
  • 206