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 isnull
?– Jéf Bueno
You don’t have to
Conn.Close();
in thecatch
and in thefinally
. Thefinally
at all times will be executed even if the run falls on the catch.– Jéf Bueno
Return to Execscalar and error: "Specified conversion is not valid."
– Victor Freitas
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.
– Jéf Bueno
It looks like it is returning a System.Int64
– Victor Freitas
Why do you think that? If it is returning that same, you need to change the conversion of
int
forlong
, that if it is really a very large number. Otherwise you can useConvert.ToInt32(ConnectionPostgres.ExecScalar(sql));
.– Jéf Bueno
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.
– Victor Freitas
It is impossible to cast explicit
long
forint
.– Jéf Bueno