Returning a single row

前端 未结 10 1430
轻奢々
轻奢々 2021-02-13 06:55

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:23

    Instead of:

     using (reader = command.ExecuteReader())
     {
          reader.Read();
          return reader["col_1"];
     }
    

    You need to cast the reader["col_1"] to string, either reader["col_1"].ToString() or reader.GetString(0) like:

    return reader.GetString(0);
    
    0 讨论(0)
  • 2021-02-13 07:28

    reader["col_1"] returns object.

    You want something like reader.GetString(reader.GetOrdinal("col_1")).

    Edit -> I just wanted to add a note here that, in addition to the concerns others have raised, a SELECT TOP without an ORDER BY can give you random results based on schema changes and/or merry-go-round scans.

    0 讨论(0)
  • 2021-02-13 07:35

    To me it seems, you don't want a single row, only a single value:

    SqlConnection sqlConnection = new SqlConnection("Your Connection String");
    SqlCommand cmd = new SqlCommand();
    Object returnValue;
    
    cmd.CommandText = "SELECT TOP 1 col_name FROM Customers";
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlConnection1;
    
    sqlConnection.Open();
    
    returnValue = cmd.ExecuteScalar();
    
    sqlConnection.Close();
    
    return returnValue.ToString(); //Note you have to cast it to your desired data type
    
    0 讨论(0)
  • 2021-02-13 07:35

    reader["col_1"] returns an object. I assume your function has a return type of string, which is where the error is coming from, it cannot implicitly convert the object to a string.

    You probably expect a string returned from col_1 so you can just cast it: (string)reader["col_1"].

    0 讨论(0)
  • 2021-02-13 07:38

    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;
    }
    
    0 讨论(0)
  • 2021-02-13 07:39

    You can use an if statement if your query only returns one value

    [...]
    string x = string.Empty;
    if(reader.Read()) {
        // make sure the value is not DBNull
        if(DBNull.Value != reader["col_1"]) {
           x = reader.GetString(0);
        }
    }
    [...]
    
    0 讨论(0)
提交回复
热议问题