Reading int values from SqlDataReader

后端 未结 6 1409
遥遥无期
遥遥无期 2021-02-02 08:18

hi can anyone please help me with this fetching from database of int values im having difficulty in fetching int values , it works for varchar but not int can someone help me ou

相关标签:
6条回答
  • 2021-02-02 08:29

    you can use

    reader.GetInt32(3);
    

    to read an 32 bit int from the data reader.

    If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

    Have you considered using

    reader.GetInt32(reader.GetOrdinal(columnName)) 
    

    rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.

    0 讨论(0)
  • 2021-02-02 08:31
    TxtFarmerSize.Text = (int)reader[3];
    
    0 讨论(0)
  • 2021-02-02 08:35

    Use the GetInt method.

    reader.GetInt32(3);
    
    0 讨论(0)
  • 2021-02-02 08:35

    Call ToString() instead of casting the reader result.

    reader[0].ToString();
    reader[1].ToString();
    // etc...
    

    And if you want to fetch specific data type values (int in your case) try the following:

    reader.GetInt32(index);
    
    0 讨论(0)
  • This should work:

    txtfarmersize = Convert.ToInt32(reader["farmsize"]);
    
    0 讨论(0)
  • 2021-02-02 08:53

    based on Sam Holder's answer, you could make an extension method for that

    namespace adonet.extensions
    {
      public static class AdonetExt
      {
        public static int GetInt32(this SqlDataReader reader, string columnName)
        {
          return reader.GetInt32(reader.GetOrdinal(columnName));
        }
      }
    }
    

    and use it like this

    using adonet.extensions;
    
    //...
    
    int farmsize = reader.GetInt32("farmsize");
    

    assuming there is no GetInt32(string) already in SqlDataReader - if there is any, just use some other method name instead

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