简体   繁体   中英

C# InvalidCastException when returning single value from SQL database

I am trying to return a value from a SQL database. However everytime I execute the following method I get an error stating, "InvalidCastException was unhandled. Object cannot be cast from DBNull to other types."

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. 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. This type cannot be cast to an 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 ).

This can't be converted to an Int32 , as integers are value types and cannot be 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.

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. Not convert directly the result of the query to 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.

Probably what you can do is ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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