Domanda

I am creating an app in which i am inserting a data in the table. After inserting the data in the table i want to get the id of that row so i can do further operation depending on it. I tried to use last_insert_rowid() function of sqlite but found no luck. can any one tell which is the best way to get last inserted row id. Any idea is appreciated. Thanks in advance.

È stato utile?

Soluzione

You can get the id of the last insert on a table like this -

tx.executeSql("INSERT INTO profile('name','label','list_order','category') values(?,?,?,?)", 
    [currentProfile.name, currentProfile.label, currentProfile.list_order, currentProfile.category], 
    function(tx, results){
        var lastInsertId = results.insertId; // this is the id of the insert just performed
    }, 
    failCB
)

The results.insertId in WebSQL is similar to mysql_insert_id() in MySQL -

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());

Altri suggerimenti

Do you have a column in your table named rowid, oid, or _rowid_? If you do, that will cause an issue with last_insert_rowid() working as intended. See here.

A workaround: If you have an ID column that is auto-incremented, you could use the following SQL to get the last entry.

SELECT * FROM yourTable ORDER BY yourIdColumn DESC LIMIT 1

It's hacky, but it would work.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top