Click here to Skip to main content
15,912,475 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am attempting to pull a SUM amount from a mySql database, using an intScalar query.

This is the calling code (The DBConnect class connects to the database):

DateTime reportStart = startDate.Date;

DBConnect reportConn = new DBConnect();
MySqlCommand reportQuery = new MySqlCommand();

reportQuery.CommandText = @"SELECT sum(amount) as total
FROM dbo.table
where created <= @startDate";

reportQuery.Parameters.Add("@startDate", MySqlDbType.Date).Value = reportStart.Date;
int xOutstanding = reportConn.intScalar(reportQuery);
lblRewardsDateX.Text = xOutstanding.ToString();

And the intScalar:

public int intScalar(MySqlCommand cmd)
      {
          int returnInt = -1;

          try
          {
              this.OpenConnection();
              cmd.Connection = connection;

              //ExecuteScalar will return one value
              returnInt = Convert.ToInt32(cmd.ExecuteScalar());
              this.CloseConnection();
              return returnInt;

          }
          catch (Exception ex)
          {
              MessageBox.Show(ex.Message);
          }
          return returnInt;
      }

However, it is throwing an exception:
Object cannot be cast from DBNull to other types.


I have double-checked the parameter being passed to the command, and it is not null. So why is it throwing the exception?

What I have tried:

Analyzed the parameter to ensure it is not a null value
Posted
Updated 19-Aug-20 9:39am
Comments
[no name] 19-Aug-20 13:08pm    
Return an object and cast / type to see what it actually returns. Reality cares nothing about what we think.

If you do a SUM on no rows you get NULL back, so there are no rows that satisfy your query. You can handle this in your code by seeing if ExecuteScalar returns DNBull and if it does assume the value is 0 (or whatever you want to do in that circumstance) and if it isn't then convert to int. Or you could handle it in your SQL doing something like

SELECT IFNULL(sum(amount), 0) as total ...


That will return 0 if SUM is null otherwise returns the sum. That way your SQL is guaranteed to return a number so you know your conversion to int will work.
 
Share this answer
 
Updating the SELECT statement in the query to

SELECT IFNULL(sum(amount), 0) as total


worked!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900