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;
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