-1

I need to retrieve the id of the row inserted just now. ie, i have a table for words and a table for meaning. i need the wordId of the word i insert in the table for words and that wordId is used for inserting the meaning in meaning table. Can anyone help me out??

I thought i could use trigger and tried the trigger:

"CREATE TRIGGER IF NOT EXISTS word_insert_trigger AFTER INSERT ON tb_words BEGIN select NEW.word_id from tb_words; END;"

like this. i tried this in sqlite dbbrowser. but it didn't work out.

i need the row id when i insert a row like this :"insert into tb_words(word_name) values('test');"

How can i do that without using "SELECT last_insert_rowid()"? like in the following link: How to retrieve the last autoincremented ID from a SQLite table?

devu mani
  • 337
  • 6
  • 12
  • 2
    Possible duplicate of [How to retrieve the last autoincremented ID from a SQLite table?](https://stackoverflow.com/questions/2127138/how-to-retrieve-the-last-autoincremented-id-from-a-sqlite-table) – Sami Kuhmonen Apr 21 '19 at 07:40
  • Do the Android sqlite bindings not provide a wrapper for `sqlite3_last_insert_rowid()`? – Shawn Apr 21 '19 at 09:05
  • @SamiKuhmonen I already saw that answer and Actually i wanted an answer other than that. that's why i asked this question here again – devu mani Apr 22 '19 at 07:02
  • Could you explain why you want some other answer than the one that works? – Sami Kuhmonen Apr 22 '19 at 07:06
  • Sorry actually it was a thinking mistake, i thought with that answer if we enter two words at a time we only get the last words id. But i forgot it is our local db and we can't enter two words at a time here. I shouldn't have mentioned SQLite, if we are inserting directly to server through api we can't use that answer. There the problem of two rows at a time exists. – devu mani Apr 22 '19 at 07:15

1 Answers1

2

No need for a trigger. Use the SQliteDatabase insert method. It returns the id (as a long) (more correctly it returns the rowid and assuming that the word_id column has been defined as an alias of the rowid column, then the returned value will be the value assigned to the word_id column).

An alias of the rowid column is defined if word_id INTEGER PRIMARY KEY is coded (the AUTOINCREMENT key may be used BUT in generally should not be used).

You may wish to read SQLite AUTOINCREMENT and/or Rowid Tables

Instead of something like :-

db.execsql("insert into tb_words(word_name) values('test');");

You would use something like :-

ContentValues cv = new ContentValues();
cv.put("word_name","test");
long word_id = db.insert("tb_words",null,cv);
MikeT
  • 51,415
  • 16
  • 49
  • 68