Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite Last Insert Rowid Does Not Work

Tags:

c#

sqlite

I found several examples of how to get the last inserted row id from an 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 I sent in and how I used it. Obviously, I misunderstood something. Could someone help me out here?

I am trying to return the ID number that was 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 have set up the table so that ID is supposed to be auto generated using the Create SQL below, but the table only stores -1 for the ID values unless I manually insert it.

public const string SQL_CREATE = "CREATE TABLE Dates1 " +
  "(ID INTEGER PRIMARY KEY AUTOINCREMENT, TaskID INTEGER, Last1 TEXT);";
like image 244
jp2code Avatar asked Dec 31 '11 00:12

jp2code


1 Answers

To quote from the SQLite documentation:

last_insert_rowid() The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

So you need to change your statement to:

"SELECT last_insert_rowid();"

because what you did was to try and call the C API function.

like image 119
ChrisWue Avatar answered Sep 24 '22 08:09

ChrisWue