0

I have an access data base where i want to add a row in a table. but I want to get the id(colum name -> id) back.

this is the code i use to register a new group:

int id;

internal static void agregarGrupo(int grado, char grupo, String escuela, int maestro)
    {
        try
        {
            comand.Connection = conection;
            comand.CommandText = 
                "INSERT INTO Grupos " +
                "(grado, grupo, escuela, maestro) " +
                "VALUES(" + grado + ", '" + grupo + "' , '" + escuela + "', " + maestro + ")";

            conection.Open();
            id = comand.ExecuteScalar();
        }
        finally
        {
            conection.Close();
        }
    }

what am I doing wrong? how can I get the id of the new row without making a new query asking for the bigest id in the table?

YowE3K
  • 23,852
  • 7
  • 26
  • 40

1 Answers1

0

You have to make another query to get the last identity value inserted because Access does not support batch commands. You need to reuse the connection and issue another command like this:

string query = "SELECT @@IDENTITY";
var cmd = new OleDbCommand(query, (OleDbConnection)command.Connection);
int newId = (int)cmd.ExecuteScalar();

Or you can simply do this after this line of code you have:

id = comand.ExecuteScalar(); // this is your code
command.CommandText = "SELECT @@IDENTITY";
int newId = (int)command.ExecuteScalar();
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64