Specified conversion is not valid in Executescalar

Asked

Viewed 1,359 times

3

The specified conversion error is not valid happens in the code:

if (command.ExecuteScalar() == DBNull.Value)
{
    resultados[j2][i2] = 0;
}
else 
{
    resultados[j2][i2] = (double)(decimal)command.ExecuteScalar(); /* <<---- */
}

The query I’m running in mysql is:

SELECT IFNULL(AVG(VL_M4000010),0) 
FROM HT_MA4_ESS_SEG 
WHERE YEAR(TS_SAMPLETM) = 2015 
    AND MONTH(TS_SAMPLETM) = 1 
    AND TIME(TS_SAMPLETM) 
    BETWEEN '00:00:00' AND '00:15:00'

The result of query via Mysql Workbench is 0.

I’ve tried the conversion without the (decimal) only with the (double), so that would be (double)command.ExecuteScalar();.

2 answers

3


I will consider that the type of resultados is double. So make a conversion instead of a cast:

Convert.ToDouble(command.ExecuteScalar());

There’s no point in using the TryParse() here because this data can be converted always.

  • Perfect, it worked! Thank you very much!

0

Another alternative is to use the Double.TryParse.

string value;
double number;

value = Double.MinValue.ToString();
if (Double.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("{0} is outside the range of a Double.", 
                     value);

value = Double.MaxValue.ToString();
if (Double.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("{0} is outside the range of a Double.",
                     value);

Example taken from: https://msdn.microsoft.com/pt-br/library/3s27fasw(v=vs.110). aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.