2013-10-16 21 views
4

我正在創建一個應用程序,我在表中插入數據。在表中插入數據後,我想獲取該行的ID,以便根據它進行進一步操作。 我試圖用last_insert_rowid()函數的sqlite,但發現沒有運氣。 任何人都可以知道哪個是獲取最後插入的行ID的最佳方式。 任何想法表示讚賞。 在此先感謝。如何從手機中的sqlite中獲取最後一個插入的行ID android

+0

last_insert_rowid()應該有工作。你的插入是否完成? – SHANK

+0

希望您使用正確的查詢SELECT last_insert_rowid()。不要包含表名 – SHANK

+0

我可能以錯誤的方式使用它,你可以給我一個例子,以及如何將結果傳遞給變量。 –

回答

4

你可以在這樣的表的最後插入的ID -

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 
) 

中的WebSQL的results.insertId是在MySQL類似mysql_insert_id() -

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

你的表中有一列名爲rowid,oid或_rowid_嗎?如果這樣做,那將導致last_insert_rowid()按預期工作的問題。見here

解決方法: 如果您有一個自動遞增的ID列,則可以使用以下SQL來獲取最後一個條目。

SELECT * FROM yourTable ORDER BY yourIdColumn DESC LIMIT 1 

這是hacky,但它會工作。

+0

如果您還從數據庫中刪除記錄,則這不起作用。新記錄取出已刪除記錄的ID – sga4

相關問題