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).
From the documentation for INSERT in SQLite:
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.
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With