0

I want to insert into two tables at a time.

This needs to be done this way.

Insert single row into one table, get the auto incremented primary key and insert multiple rows into other table, using the primary key value I got from the first table as reference.

What is the best way to do this?

2 Answers 2

1

SQLite has the built-in last_insert_rowid() function, but its return value would change after the next insertion.

You have to read the value in your program, and insert it manually:

db.execute("INSERT INTO People(Name) VALUES (?)", ["Joe"])
id = db.last_insert_rowid
db.execute("INSERT INTO Pets(Owner, Name) VALUES (?,?)", [id, "Fluffy"])
db.execute("INSERT INTO Pets(Owner, Name) VALUES (?,?)", [id, "Spot"])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you.Is it same as taking the return value of getWritableDatabase().insert and using that key as reference?
Yes (and if you want to know how to do this on Android, you should habe mentioned this in the question).
0

It depends on how you're incrementing the key. If you are storing the current "next key value" in another table, then first extract the next key, and use it for all your insert statements. Finally increment the "next key value" in the other table.

2 Comments

I am using autoincremented key
Ok, I realized that after I posted, my apologies.

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.