Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert data into two tables at once using SQLiteDatabase in Android?

So lets say I have this code:

SQLiteDatabase sqlDB = database.getWritableDatabase();
long iD = 0;
iD = sqlDB.insert(Table1, null, TestV);

Can I somehow rewrite this to insert into two tables instead of one? My problem is that 'values' returns 3 values from one table, and 1 value from another. Therefore, the 1 value that isn't in 'Table1' sets off an error that the column cant be found in 'Table1.' Is there a way to do this? If not then should I do two separate inserts? I am confused as how to insert data into two tables in one database (Tables are Relational: one has a foreign key).

like image 310
john Avatar asked Dec 16 '22 11:12

john


2 Answers

From the documentation for INSERT in SQLite:

enter image description here

Note that the flowchart doesn't give you an opportunity to post into more than one table at once. SQLiteDatabase.insert() is a convenience method for using the INSERT statement.

like image 194
MowDownJoe Avatar answered May 14 '23 07:05

MowDownJoe


You can simulate this using database transaction:

    SQLiteDatabase db = getWritableDatabase();

    db.beginTransaction();

    try {

        db.execSQL("insert into table1...");
        db.execSQL("insert into table2...");

        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

You may need to choose the order of the inserts if there are dependencies between the values inserted, for instance if there's a foreign key relationship: ( insert to table1 and then table2, or first insert to table2...)

like image 41
m.ghoreshi Avatar answered May 14 '23 06:05

m.ghoreshi