Returning a single row

前端 未结 10 2368
野的像风
野的像风 2021-02-13 06:58

I\'m trying to return a single row from a database:

using (connection = new SqlConnection(ConfigurationManager.AppSettings[\"connection\"]))
{
    using (command         


        
10条回答
  •  时光取名叫无心
    2021-02-13 07:37

    This is how I would style (and fix) the code:

    using (var connection = new SqlConnection(ConfigurationManager.AppSettings["connection"]))
    using (var command = new SqlCommand(@"select top 1 col_1, col_2 from table1", connection))
    {
        connection.Open();
    
        using (var reader = command.ExecuteReader())
        {
            if (reader.Read()) // Don't assume we have any rows.
            {
                int ord = reader.GetOrdinal("col_1");
                return reader.GetString(ord); // Handles nulls and empty strings.
            }
    
            return null;
        }
    }
    

    Using the index reader[] will give you object types, these need casting. However, I hardly touch that style and always favour the slightly more verbose, but more robust use of ordinals and asking for types in a strongly-typed manner.

    If you only need the value in the first column of the first row, you can use ExecuteScalar instead, again this returns an object that can be cast and doesn't need a reader:

    using (var connection = new SqlConnection(ConfigurationManager.AppSettings["connection"]))
    using (var command = new SqlCommand(@"select top 1 col_1, col_2 from table1", connection))
    {
        connection.Open();
    
        var result = command.ExecuteScalar();
        return result == null ? "" : (string)result;
    }
    

提交回复
热议问题