SQLite Last Insert Rowid not working

I found some examples of how to get the last inserted row id from the sql insert call to my SQLite database, but my script threw this error:

SQLiteException Message = "SQLite error\r\nnear \")\": syntax error" InnerException NULL 

Below is the SQL text that I sent, and how I used it. Obviously, I didnโ€™t understand something. Can anyone help me here?

I am trying to return the identification number just inserted.

 private static int Save(Dates date, SQLiteConnection con) { // REF: http://www.sqlite.org/c3ref/last_insert_rowid.html int result = 0; string sql = "INSERT INTO Dates1 " + "(ID, TaskID, Last1) " + "VALUES " + "((SELECT MAX(ID) FROM Dates1)+1, @TaskID, @Last); " + "SELECT sqlite3_last_insert_rowid(sqlite3*);"; using (SQLiteCommand cmd = new SQLiteCommand(sql, con)) { cmd.Parameters.AddWithValue(Dates.AT_TASK, date.TaskID); cmd.Parameters.AddWithValue(Dates.AT_LAST, date.Last.ToShortDateString()); cmd.CommandText = Dates.SQL_INSERT; try { result = cmd.ExecuteNonQuery(); } catch (SQLiteException err) { result = -1; LogError("Save(Dates, SQLiteConnection)", err); } } return result; } 

FYI: I configured the table so that the ID should be automatically generated using Create SQL below, but the table saves -1 for the ID if I did not insert it manually.

 public const string SQL_CREATE = "CREATE TABLE Dates1 " + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, TaskID INTEGER, Last1 TEXT);"; 
+7
source share
1 answer

For a quote from the SQLite documentation:

last_insert_rowid () The last_insert_rowid () function returns the ROWID of the last row inserted from the database connection that calls this function. The last_insert_rowid () SQL function is a wrapper around the C / C ++ sqlite3_last_insert_rowid () interface function.

So, you need to change your statement to:

 "SELECT last_insert_rowid();" 

because you tried to call the C API function.

+13
source

All Articles