How to insert data into two tables at once using S

2019-07-07 05:54发布

问题:

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).

回答1:

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.



回答2:

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...)