Conversion specified is not valid in ExecuteScalar

3

The specified conversion error is not valid 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 converting (decimal) to only (double) , so it would be (double)command.ExecuteScalar(); .

    
asked by anonymous 26.01.2016 / 20:40

2 answers

2

I'll assume that the type of resultados is double . Then do a conversion instead of a cast :

Convert.ToDouble(command.ExecuteScalar());
    
26.01.2016 / 20:46
0

Another alternative is to use 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: link

    
29.01.2016 / 03:33