SQLite的最后插入ROWID不起作用
我发现如何从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
,但该表只存储-1
为ID
值,除非我手动插入。
public const string SQL_CREATE = "CREATE TABLE Dates1 " +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT, TaskID INTEGER, Last1 TEXT);";
要从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函数是什么。
Shazam!就是这样。谢谢。我无法在文档中找到它。 – jp2code 2011-12-31 01:47:08
您是使用'System.Data.SQLite'(http://sqlite.phxsoftware.com/)还是使用.NET的其他SQLite包装? – 2011-12-31 00:28:43
是的,'System.Data.SQLite'。 – jp2code 2011-12-31 01:45:06