How to use executeReader() method to retrieve the value of just one cell

前端 未结 4 847
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 04:06

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 =          


        
相关标签:
4条回答
  • 2020-12-06 04:51

    ExecuteScalar() is what you need here

    0 讨论(0)
  • 2020-12-06 05:01
    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"))
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-06 05:04

    Duplicate question which basically says use ExecuteScalar() instead.

    0 讨论(0)
  • 2020-12-06 05:07

    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.

    0 讨论(0)
提交回复
热议问题