繁体   English   中英

我有一个错误,无法将对象从DBNull强制转换为其他类型?

[英]I have a error Object cannot be cast from DBNull to other types?

我的代码是:我在做断点时正在检索数据氟利昂数据库,它在列表中显示数据,但它也给我一个错误

    public static List<StudentScore> GetAllScore()
   {
       SqlConnection conn = MyDB.GetConnection();
       string selectStm = "SELECT en.CourseID,en.Score,s.StudentID FROM EnrollmentTable en,Student s WHERE en.StudentID = s.StudentID";
       SqlCommand command = new SqlCommand(selectStm, conn);
       List<StudentScore> aStudentScore = new List<StudentScore>();
       try
       {
           conn.Open();
           SqlDataReader reader = command.ExecuteReader();          
           Console.WriteLine(reader.HasRows.ToString());
           while (reader.Read())
           {
               StudentTable st = new StudentTable();
               CourseTable cr = new CourseTable();
               Enrollment enr = new Enrollment();
               StudentScore score = new StudentScore();
               enr.CourseData = cr;
               enr.StudentData = st;                                    
                   //score.EnrollmentData.StudentData.StudentID = reader["StudentID"].ToString();
                   //score.EnrollmentData.CourseData.CourseID = reader["CourseID"].ToString();                  
                   st.StudentID = reader["StudentID"].ToString();
               cr.CourseID = reader["CourseID"].ToString();
               score.Score = Convert.ToInt32(reader["Score"]);
               score.EnrollmentData = enr; 
               aStudentScore.Add(score);
           }
           reader.Close();
           return aStudentScore;
       }
       catch (SqlException ex)
       {
           throw ex;
       }
       finally
       {
           conn.Close();
       }

   }


}

}

它从数据库中获取数据,但向mw显示此错误.....无法将对象从DBNull强制转换为其他类型,所以这是什么意思,请告诉我如何解决?

这意味着您在数据库中有一个NULL值。 您必须在代码中检查它,或将列模式更改为NOT NULL

st.StudentID = reader["StudentID"] == DBNull.Value ? null : reader["StudentID"].ToString();
cr.CourseID = reader["CourseID"] == DBNull.Value ? null : reader["CourseID"].ToString();
score.Score = reader["Score"] == DBNull.Value ? 0 : Convert.ToInt32(reader["Score"]);

您现在必须处理C#对象中的null值。

您需要检查阅读器是否为DBNULL类型

在尝试对其进行转换之前,请在读取器上调用IsDBNull()以检查该列:

using (reader = server.ExecuteReader(CommandType.Text, TopIDQuery, paramet))
{
   while (reader.Read())
   {
       var column = reader.GetOrdinal("TopID");

       if (!reader.IsDBNull(column))
          topID = Convert.ToInt32(reader[column]);
       }
   }
}

或者,与DBNull.Value进行比较:

var value = reader["TopID"];

if (value != DBNull.Value)
{
    topID = Convert.ToInt32(value);
}

DBNull用于表示数据库中的空值。

您应该在转换ir之前检查该值是否不是DBNull。

object score = reader["Score"];

score.Score = score == DBNull.Value ? 0 : Convert.ToInt32(score);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM