简体   繁体   English

从SQL数据库返回单个值时,C#InvalidCastException

[英]C# InvalidCastException when returning single value from SQL database

I am trying to return a value from a SQL database. 我正在尝试从SQL数据库返回一个值。 However everytime I execute the following method I get an error stating, "InvalidCastException was unhandled. Object cannot be cast from DBNull to other types." 但是,每次执行以下方法时,都会出现错误,指出“未处理InvalidCastException。无法将对象从DBNull强制转换为其他类型。”

Any light you could shed on this would be greatly appreciated. 您可能会对此有所了解,将不胜感激。 The method I am using is as follows. 我使用的方法如下。

Thanks. 谢谢。

    public static int ScrapTotal2(string prdTypeV, string startDateV, string prtCodeV)
    {
        int scrapTotal2;

        SqlParameter prdType = new SqlParameter("@prdType", SqlDbType.VarChar);
        prdType.Value = prdTypeV;
        SqlParameter startDate = new SqlParameter("@startDate", SqlDbType.VarChar);
        startDate.Value = startDateV;
        SqlParameter prtCode = new SqlParameter("@prtCode", SqlDbType.VarChar);
        prtCode.Value = prtCodeV;

        SqlCommand scrapTotal2SC = new SqlCommand("SELECT SUM([QTY_SCRP]) FROM [TBL_PRDMST] WHERE [PRD_CODE] LIKE @prdType AND [PRD_DATE] = @startDate AND [PRT_CODE] LIKE @prtCode", DataAccess.myConnection);
        scrapTotal2SC.Parameters.Add(prdType);
        scrapTotal2SC.Parameters.Add(startDate);
        scrapTotal2SC.Parameters.Add(prtCode);

        DataAccess.myConnection.Open();
        scrapTotal2 = Convert.ToInt32(scrapTotal2SC.ExecuteScalar());
        DataAccess.myConnection.Close();

        return scrapTotal2;
    }

Your SELECT statement returns NULL value. 您的SELECT语句返回NULL值。 You have to check if it is null first: 您必须先检查它是否为空:

object result = scrapTotal2SC.ExecuteScalar();
if (result == DBNull.Value) 
{ 
    /* write your code */ 
}
else
{
    scrapTotal2 = Convert.ToInt32(result);
}

Since you didn't specify, I'm going to assume that this line is the problem: 由于您未指定,因此我假设这是问题所在:

scrapTotal2 = Convert.ToInt32(scrapTotal2SC.ExecuteScalar());

When you get a NULL in a database, it will be cast to a type of DBNull in your code. 当您在数据库中获得NULL时,它将在代码中转换为DBNull类型。 This type cannot be cast to an Int32 . 此类型不能强制转换为Int32

You can check for it like this: 您可以像这样检查它:

var obj = scrapTotal2SC.ExecuteScalar()
if (obj == DBNull.Value)
{
    // whatever logic you want to handle nulls
} else {
    scrapTotal2 = Convert.ToInt32(obj);
}

Seems like the error message is clear - your query returns null (which in .NET would be a DbNull ). 似乎错误消息很清楚-您的查询返回null (在.NET中为DbNull )。

This can't be converted to an Int32 , as integers are value types and cannot be null . 这不能转换为Int32 ,因为整数是值类型,不能为null

Either check the return value for DbNull and return a default value from your data layer, or check your query and database to ensure that a null will not be returned. 检查DbNull的返回值并从数据层返回默认值,或者检查查询和数据库以确保不返回null

Some SQL server think that sum of empty list is null and not 0. So you have to handle the conversion from null to int yourself. 一些SQL Server认为空列表的总和为null而不是0。因此,您必须自己处理从null到int的转换。 Not convert directly the result of the query to int. 不直接将查询结果转换为int。

尝试scrapTotal2 = Convert.ToInt32(((string)scrapTotal2SC.ExecuteScalar()));

The error message is because the return value is NULL and that you are trying to store in a INT type variable ... which can't be done. 该错误消息是因为返回值为NULL ,并且您试图将其存储在INT类型变量中……这是无法完成的。

Probably what you can do is ... 可能您可以做的是...

if(retval is null) then assign var = 0.

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

相关问题 使用C#从SQL Server数据库打印单个值 - Print Single Value from SQL Server Database using C# C# - 从 HttpSessionState 读取时出现 InvalidCastException - C# - InvalidCastException when reading from HttpSessionState System.InvalidCastException:尝试在 C# 中使用实体框架将对象添加到 SQL 数据库时 - System.InvalidCastException: When trying to add an object to a SQL database using Entity Framework in C# 如何检测数据库SQL LINQ C#中何时没有值 - How to detect when there is no value from database SQL LINQ C# 从c#中的数据表中获取最大值代码抛出InvalidCastException - Get Maximum value code from a datatable in c# throws InvalidCastException C#-从sqlite获取双精度时的InvalidCastException - C# - InvalidCastException when fetching double from sqlite 从C#客户端调用COM方法时,InvalidCastException - InvalidCastException when calling COM method from C# client 尝试从TimerCallback访问webbrowser控件时C#“InvalidCastException” - C# “InvalidCastException” when trying to access webbrowser control from TimerCallback C#-从数据表以字符串形式返回单个值(任何数据类型) - C# - Returning a single value (any datatype) from a DataTable as a string 标量值 function 来自 SQL 从 C# 调用时服务器不返回值 - Scalar valued function from SQL Server not returning value when called from C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM