Is there any built in function available in SQLite to fetch last inserted row id.
For eg :- In mysql we have LAST_INSERT_ID()
this kind of a function. For sqllite any function available for doing the same process.
Please help me.
Thanks
Is there any built in function available in SQLite to fetch last inserted row id.
For eg :- In mysql we have LAST_INSERT_ID()
this kind of a function. For sqllite any function available for doing the same process.
Please help me.
Thanks
It has last_insert_rowid()
The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function
I'm new to SQLite and this thread is quite old so I thought it may need an update as I feel there is a simpler and shorter method of getting the 'id' of the last inserted row. I used ->querySingle()
instead of ->exec()
and included at the end of my SQL statement returning id
.
I feel this is probably more reliable and thread-safe since it's the result of the actual insert statement. Maybe even lighter processing on resources.
$id = $db->querySingle("insert into names (first, last) values ('john', 'do') returning id;");
This is a short C# method that is working for me. Int32 is large enough for my purposes.
public static Int32 GetNextID( SqliteConnection AConnection )
{
Int32 result = -1;
using ( SqliteCommand cmd = AConnection.CreateCommand() )
{
cmd.CommandText = "SELECT last_insert_rowid();";
using ( SqliteDataReader r = cmd.ExecuteReader() )
{
if ( r.Read() )
result = (Int32) r.GetInt64( 0 );
}
}
return result;
}
SQLite
This is available using the SQLite
last_insert_rowid()
function:PHP
The PHP version/binding of this function is
sqlite_last_insert_rowid()
: