Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mono.Data.Sqlite on Monotouch: How to get the value of an autoincrement field after inserting a row?

OK, this is probably pretty basic stuff, but it took me quite some time to figure it out. And I guess there are a lot more .NET programmers like me, new to Monotouch and SQLite who don't know this.

I use Ado.NET (System.Data) with Monotouch and SQLite. In SQLite, every row of every table has an 64-bit signed integer called ROWID. You can use this, or if you prefer you can specify a field with INTEGER PRIMARY KEY AUTOINCREMENT, which SQLite will link to ROWID.

But how do you retrieve the value of this field after inserting a new record? Something like the @@identity keyword in Sql Server?

Searching around I found that the c-library for iOS of SQLite has a method sqlite3_last_insert_rowid() to retrieve this, but there is no equivalent of that in Mono.Data.Sqlite. In an older implementation (Mono.Data.SqliteClient) there was a LastInsertRowID() method, but that method disappeared in Mono.Data.Sqlite. Why?

like image 432
Marcel W Avatar asked Dec 21 '10 15:12

Marcel W


People also ask

How to get ID of inserted row in SQLite?

SQLite has a special SQL function – last_insert_rowid() – that returns the ID of the last row inserted into the database so getting the ID of a new row after performing a SQL insert just involves executing the last_insert_rowid() command.

How does auto increment work in SQLite?

AUTOINCREMENT guarantees that automatically chosen ROWIDs will be increasing but not that they will be sequential. Because AUTOINCREMENT keyword changes the behavior of the ROWID selection algorithm, AUTOINCREMENT is not allowed on WITHOUT ROWID tables or on any table column other than INTEGER PRIMARY KEY.


1 Answers

SQLite has some internal core functions. One of these functions is last_insert_rowid(). So all you have to do is to issue a command "SELECT last_insert_rowid()". Example in Monotouch:

    public long GetLastInsertRowId(SqliteConnection connection)
    {
        // Assuming connection is an open connection from your INSERT
        using (SqliteCommand command = new SqliteCommand("SELECT last_insert_rowid()", connection))
        {
            return (long)command.ExecuteScalar();
        }
    }

Or you can combine the select with your insert, example:

string SqlCommand = "INSERT into Customers ([Name], .... [City]) VALUES (@Name, ... @City);SELECT last_insert_rowid();";
like image 78
Marcel W Avatar answered Nov 08 '22 05:11

Marcel W