Error conversion type Object to int

Asked

Viewed 562 times

0

I am making a select in the database, using Execscalar returning an Object but I cannot cast this value returned to integer.

public static int ConsultaPDVsAtivos()
{
    NpgsqlCommand sql = new NpgsqlCommand();
    sql.CommandText = "SELECT COUNT(ID) " +
                      "FROM PDV " +
                      "WHERE ATIVO = TRUE;";

    int pdv_count = (int)ConnectionPostgres.ExecScalar(sql); //ERRO
    return pdv_count;
}

Method of consulting in the bank:

//Executa comando com retorno no banco de dados. param: FbCommand
public static object ExecScalar(NpgsqlCommand SqlCommand)
{
    NpgsqlConnection Conn = null;
    try
    {
        // Abre banco de dados 
        Conn = AbreBD();
        SqlCommand.Connection = Conn;
        return SqlCommand.ExecuteScalar();

    }
    catch (Exception erro)
    {
        MessageBox.Show(String.Format("Erro ao tentar Criar o Objeto Command: \n ERRO: {0}\n FAVOR ENTRAR EM CONTATO COM NOSSO SUPORTE!", erro.Message));
        Conn.Close();
        return false;
    }
    finally
    {
        Conn.Close();
    }
}
  • And you know if the return of ExecScalar has something or is null?

  • 1

    You don’t have to Conn.Close(); in the catch and in the finally. The finally at all times will be executed even if the run falls on the catch.

  • Return to Execscalar and error: "Specified conversion is not valid."

  • 3

    You need to know what is the return of your method. If you are popping this error you said, the return is not simply a whole "boxed" in an Object.

  • It looks like it is returning a System.Int64

  • Why do you think that? If it is returning that same, you need to change the conversion of int for long, that if it is really a very large number. Otherwise you can use Convert.ToInt32(ConnectionPostgres.ExecScalar(sql));.

  • declared an Object to receive the value and made a Gettype() in this variable Object: System.Int64 and Convert.Toint32 worked, but I found it strange not to be able to make an explicit cast.

  • 1

    It is impossible to cast explicit long for int.

Show 3 more comments

1 answer

1


According to comments, the return of ConnectionPostgres.ExecScalar(sql) is a long boxed in a object.

Like long accepts numbers much larger than int, the cast explicit is unfeasible. So you can try to make a conversion to int, thus:

 int pdv_count = Convert.ToInt32(ConnectionPostgres.ExecScalar(sql));

Be careful with this, because if the return is greater than the maximum value of a int (int.MaxValue - 2147483647) conversion will fail.

Browser other questions tagged

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