从SqlDataReader对象读取的int值 [英] Reading int values from SqlDataReader

查看:436
本文介绍了从SqlDataReader对象读取的int值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好任何人都可以请帮我这个从int值的数据库中获取即时通讯中获取的int值有困难的,它为VARCHAR,但不是int有人可以帮我请

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 out please

if (int.TryParse(TxtFarmerCode.Text, out intValue))
{
   using (SqlConnection sqlConn = new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True")) //here goes connStrng or the variable of it
   {
      sqlConn.Open();
      string sqlQuery = @"SELECT farmername,villagename,gender,farmsize FROM cottonpurchase WHERE farmercode = @code";

      using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
      {
         cmd.Parameters.Add("@code", SqlDbType.Int).Value = intValue;
         using (SqlDataReader reader = cmd.ExecuteReader())
         {;
            if (reader.Read())
            {
               TxtFarmerName.Text = (string)reader[0];
               TxtVillageName.Text = (string)reader[1];
               TxtGender.Text = (string)reader[2];
            }
            else
               MessageBox.Show("For Farmer Code " + intValue.ToString() + " there is no farmer in the database.");
         }
      }
   }
}

我想取txtfarmersize其数据类型为int,但不知道如何做到这一点请大家帮帮我?

i want to fetch txtfarmersize which is int but dont know how to do it please help me?

推荐答案

您可以使用

reader.GetInt32(3);

来读取数据读取器的32位整型。

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.

你有没有考虑使用

reader.GetInt32(reader.GetOrdinal(columnName)) 

而不是访问按位置。这使你的code少脆,如果你改变了查询之前,现有的添加新列不会打破。如果你要做到这一点在一个循环中,第一缓存序。

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.

这篇关于从SqlDataReader对象读取的int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆