从SqlDataReader读取int值

tan*_*nya 25 c# ado.net

嗨,任何人都可以请帮助我从int值的数据库中获取我很难获取int值,它适用于varchar但不是int可以有人帮助我请

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.");
         }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

我想获取txtfarmersize这是int但不知道该怎么做请帮帮我?

Sam*_*der 56

您可以使用

reader.GetInt32(3);
Run Code Online (Sandbox Code Playgroud)

从数据读取器读取32位int.

如果您知道数据的类型,我认为最好使用Get*强类型的方法来阅读,而不仅仅是阅读对象和强制转换.

你考虑过使用吗?

reader.GetInt32(reader.GetOrdinal(columnName)) 
Run Code Online (Sandbox Code Playgroud)

而不是按位置访问.如果您更改查询以在现有列之前添加新列,这会使您的代码不那么脆弱并且不会中断.如果要在循环中执行此操作,请先缓存序号.

  • @RayLoveless 如果值为空,您将收到异常。您可以使用 reader.IsDBNull(reader.GetOrdinal(columnName)) 检查空值并采取适当的行动。 (2认同)
  • 这是真正困扰我开发的事情之一-我一生都在努力-正确读取整数仍然需要跳过去。是的,我知道,日期和时间更糟。:(只要给我我的整数,我就可以了。对不起。 (2认同)

Bro*_*ass 14

这应该工作:

txtfarmersize = Convert.ToInt32(reader["farmsize"]);
Run Code Online (Sandbox Code Playgroud)


小智 6

使用GetInt方法.

reader.GetInt32(3);
Run Code Online (Sandbox Code Playgroud)


Geo*_*lis 6

根据 Sam Holder 的回答,你可以为此制定一个扩展方法

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

并像这样使用它

using adonet.extensions;

//...

int farmsize = reader.GetInt32("farmsize");
Run Code Online (Sandbox Code Playgroud)

假设 SqlDataReader 中没有 GetInt32(string) - 如果有,只需使用其他方法名称即可