如何从数据库中检索整数值&将它存储在.net中的整数中

时间:2014-01-04 11:33:11

标签: c# asp.net sql-server

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{

   SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select FromYear from Factory where Cal_ID='" + DropDownList1.SelectedItem.Text + "'";
    cmd.Connection = con;
    con.Open();
    dr = cmd.ExecuteReader();
    dr.Read();
    d = dr[0].ToString();
   //d =(string) Label4.Text;
    con.Close();

  }

我想要数据库中的整数值

3 个答案:

答案 0 :(得分:2)

尝试

SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select FromYear from Factory where Cal_ID='" + DropDownList1.SelectedItem.Text + "'";
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader();
dr.Read();
int d = dr.GetInt32(0);
con.Close();

dr.GetInt32(0)应读取位置0的int

答案 1 :(得分:1)

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{

   SqlCommand cmd = new SqlCommand();
   cmd.CommandType = CommandType.Text;
   cmd.CommandText = "select FromYear from Factory where Cal_ID='" + DropDownList1.SelectedItem.Text + "'";
   cmd.Connection = con;
   con.Open();

   d = GetYear(cmd).ToString();

   con.Close();
}

“脏”工作由 GetYear

完成
private const DEFAULT_YEAR = 2000;
private int GetYear(System.Data.IDbCommand command) {
   int year = DEFAULT_YEAR;
   using (System.Data.IDataReader reader = command.ExecuteReader()) {
      if (reader.Read()) {
         year = GetIntOrDefault(reader, 0);
      }
   }
   return year;
}

private  int GetIntOrDefault(System.Data.IDataRecord record, int ordinal) {
   if (record.IsDBNull(ordinal)) {
      return DEFAULT_YEAR;
   } else {
      return record.GetInt32(ordinal);
   }
}

答案 2 :(得分:0)

string InvAmountQuery = "SELECT InvAmount FROM Registration WHERE Email='" + useremail + "' ";
SqlCommand InvAmountcom = new SqlCommand(InvAmountQuery, conn);
int InvAmount = Convert.ToInt32(InvAmountcom.ExecuteScalar().ToString());