【问题标题】:InvalidCastException in returning most recently added column返回最近添加的列时出现 InvalidCastException
【发布时间】:2014-11-29 19:53:58
【问题描述】:

我想从数据库表中返回最近插入记录的最后一列。我不断收到此错误:

在 SchoolManagement.exe 中发生了“System.InvalidCastException”类型的第一次机会异常

附加信息:指定的演员表无效。

如果有这个异常的处理程序,程序可以安全地继续

代码:

public int A()
{
    string _connection = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
    string stmt = "SELECT TOP 1 RegistrationNumber FROM tblStudentBiodata ORDER BY RegistrationNumber DESC";


    int count = 0;

    using (SqlConnection thisConnection = new SqlConnection(_connection))
    {
        using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
        {
            thisConnection.Open();
            count = (int)cmdCount.ExecuteScalar();
        }
    }
    return count;
}

【问题讨论】:

    标签: c# sql


    【解决方案1】:

    你的转换为 int 抛出异常:

    count = (int)cmdCount.ExecuteScalar();
    

    你的转换是不安全的,你肯定不会从 ExecuteScalar 方法返回一个整数。事实上,ExecuteScalar 方法会将包装(装箱)的结果返回到 Object,因此请注意该对象可以包含任何类型(例如 float、decimal、int 等)。

    还要确保您不是从空值转换,因为如果表中没有记录,则会返回该值。因此,请确保在尝试强制转换之前添加检查对象是否为空。

    根据我的解释,检查 SQL Server 中 RegistrationNumber 列的类型,并确保在 C# 代码中转换为正确的类型。

    以下是 SQL Server 和 C# 之间的类型映射列表:

    http://msdn.microsoft.com/en-us/library/cc716729%28v=vs.110%29.aspx

    【讨论】:

    • RegistrationNumber 的数据类型是 varchar(50)
    【解决方案2】:

    正如在另一个答案中已经指出的那样,下面的行导致异常,并且确定 RegistrationNumber 列不是 INT 类型。我怀疑它会是 SQL CHARVARCHAR 列。

    count = (int)cmdCount.ExecuteScalar();
    

    在这种情况下,不要进行直接转换,而是尝试使用AS 运算符间接转换它并将您的count 变量声明为nullable Int 之类的

    int? count = 0;
    count = cmdCount.ExecuteScalar() as int?;
    

    然后检查并使用它

    if (count != null)
    {
       //Do something with it
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 2023-04-06
      • 2020-10-13
      相关资源
      最近更新 更多