4

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have seen this diagram before. I simply curious if there is a way around it, and if not any options.
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.