Get id of the last record inserted in the database

Asked

Viewed 2,766 times

0

I was wondering if I have how to insert a record in the database and already returns the id of this record in android sqlite

use this method to insert

public boolean insertH(HistoricoObjeto historico) {

    /* Mapa com a coluna e os valores de cada coluna. */
    ContentValues values = new ContentValues();
    values.put("datahora", historico.getDatahora());
    values.put("mensagem", historico.getMensagem());


    /* Executa um insert no banco de dados usando o mapa de valores. */
    /* Retorna -1 caso ocorra algum erro no INSERT. */
    long retorno = this.banco.insert("historico", null, values);

    if(retorno != -1)
        return true;
    else
        return false;
}
  • http://www.sqlite.org/lang_corefunc.html#last_insert_rowid

  • Have you ever thought of doing a query by returning the last record inserted in the default order.

3 answers

1

Try it this way:

SELECT * 
FROM    TABLE
WHERE   ID = (SELECT MAX(ID)  FROM TABLE);

0

public long insertH(HistoricoObjeto historico) {

/* Mapa com a coluna e os valores de cada coluna. */
ContentValues values = new ContentValues();
values.put("datahora", historico.getDatahora());
values.put("mensagem", historico.getMensagem());


/* Executa um insert no banco de dados usando o mapa de valores. */
/* Retorna -1 caso ocorra algum erro no INSERT. */
long retorno = this.banco.insert("historico", null, values);
return retorno;
}

this return gets the id in the last history inserted

0

Browser other questions tagged

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