Insert into two tables in SQLite Android

1

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

I have two Client and Address tables, the latter with a foreign key referencing the client table, and it must be registered in a single transaction. I know that MySQL has the LAST_INSERT_ROWID(); function. And in Android SQLite how do I?

    
asked by anonymous 29.06.2014 / 08:08

1 answer

3

To get the id of the last entered record, use the value returned by the SQLiteDatabase.insert()

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

To make multiple 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();
}
    
29.06.2014 / 15:40