Dave's Brain

Browse - Programming Tips - How can I find the id of the row I just inserted?

Date: 2012apr2
Language: SQLite, Java

Q.  How can I find the id of the row I just inserted?

A.  Use:

SELECT last_insert_rowid()
Here's some Java code that does that (but it can be done in any language):
public int getLastInsertRowId() { int result_id = -1; final String sql = "SELECT last_insert_rowid()"; Cursor c = null; try { c = getReadableDatabase().rawQuery(sql, null); if (c.getCount() > 0) { c.moveToFirst(); result_id = c.getInt(0); } } finally { if (c != null) { try { c.close(); } catch (SQLException e) { } } } return result_id; }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.