2011-12-31 46 views
7

我發現如何從SQL INSERT打到我的SQLite數據庫中獲取最後插入的行ID的幾個例子,但我的腳本拋出此錯誤:SQLite的最後插入ROWID不起作用

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

下面是我發送的SQL文本以及我如何使用它。顯然,我誤解了一些東西。有人可以幫我在這裏嗎?

我想返回剛剛插入的ID號。

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:我已經設置了表,以便ID應該是使用自動生成的創建以下SQL,但該表只存儲-1ID值,除非我手動插入。

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

您是使用'System.Data.SQLite'(http://sqlite.phxsoftware.com/)還是使用.NET的其他SQLite包裝? – 2011-12-31 00:28:43

+0

是的,'System.Data.SQLite'。 – jp2code 2011-12-31 01:45:06

回答

13

要從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.

所以,你需要你的語句更改爲:

"SELECT last_insert_rowid();" 

,因爲你所做的嘗試和調用C API函數是什麼。

+0

Shazam!就是這樣。謝謝。我無法在文檔中找到它。 – jp2code 2011-12-31 01:47:08