Return DB value in a variable

Asked

Viewed 439 times

1

I am trying to return the largest ID of the table Orcamento in a variable, but it returns me an error:

An unhandled Exception of type 'System.Nullreferenceexception' occurred in Mysql.Data.dll. Additional information: reference to object not defined for an object instance."

Does anyone know what it can be?

Follows the code:

public void ultimoID(int ultimoid)
{
    int resultado;
    var conn = new MySqlConnection(stringCon);
    var sql = "SELECT MAX(id_orcamento)FROM orcamento";
    var cmd = new MySqlCommand(sql, conn);
    Object retorno = cmd.ExecuteScalar();
    resultado = Convert.ToInt32(retorno);
}
  • On which line is the error??

  • In this one: Object return = cmd.Executescalar();

  • You need to see why you can’t create MySqlCommand, the error is there.

  • I got it rolling! This was missing: // Executes the cosulta cmd = new Mysqlcommand(sql, Conn); rdr = cmd.Executereader(); while (rdr.Read()) while (rdr.Read()) { string result = rdr["MAX(id_orcamento)"]. Tostring(); int resultadoid = Convert.Toint32(result); this.ultimoValor = resultadoid; }

  • This may have worked, but it’s a coincidence, and it’s a scam, because this isn’t a case for using the Reader, the correct is the scalar same. Still have error that the connection is not closed, which may be the problem. And the code can be written in 1 line.

  • got it, I tried it this way, but it gives the same error. I took only the expression and ran it in Mysql and it returns the correct result.

Show 1 more comment

1 answer

1


Swap Object for var in its return variable.

var retorno = cmd.ExecuteScalar();

If not, check if your SQL query is generating any results.

  • 1

    thanks! The Executereader was missing();

  • 1

    @Jessf, if the answer solved your problem, mark it as accepted; it’s the best way to thank (https://answall.com/tour)

Browser other questions tagged

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