Insert into two tables in Android Sqlite

Asked

Viewed 1,387 times

1

How do I add data to two tables on Android in a single transaction?

I have two tables Client and Address, is last with a foreign key referencing the client table, and must be registered in a single transaction. I know that in Mysql you have the function LAST_INSERT_ROWID();. And on Android Sqlite how do I?

1 answer

3

To obtain the id of the last inserted record use the value returned by the function SQLiteDatabase.insert()

long id = myDb.insert(...);  

To make several Inserts in a single transaction:

myDb.beginTransaction();
try {
    //inserir cliente e guardar o id gerado
    long id = myDb.insert(...);

    //Componha o registo endereço usado o id
    .........
    //inserir endereço
    myDb.insert(...);

    //Commit da transação
    myDb.setTransactionSuccessful();
}catch {
    //Erro durante a transação 
}finally {
    myDb.endTransaction();
}
  • Thanks! With your tip I managed to solve.

Browser other questions tagged

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