问题
Hya.
I have implemented FMDB in my app. I am trying to get the last row id from one of my databases with this
FMDatabase *bdb=[FMDatabase databaseWithPath:databasePath];
NSString *str;
if([bdb open]){
int lastId=[bdb lastInsertRowId];
FMResultSet *s = [bdb executeQuery:[NSString stringWithFormat:@"SELECT budget FROM data WHERE ROWID='%d'",lastId]];
if([s next])
{
str= [s stringForColumnIndex:0];
}
}
the problem i have is that lastId is always 0 , although there are 3 entries currently in the database. Any1 have any idea why is this happening?
EDIT: the database is created like this:
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &basicDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS DATA (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, BUDGET INTEGER)";
if (sqlite3_exec(basicDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
DLog(@"Failed to create table");
}
sqlite3_close(basicDB);
} else {
DLog(@"Failed to open/create database");
}
}
回答1:
lastInsertRowId
works on a specific connection.
The connection that you're using has just been opened, so there is no inserted row ID.
(The purpose of lastInsertRowId
is to allow your app to know the ID of a record that has just been INSERT
ed.)
To read data from the last record, use something like this:
SELECT budget FROM data WHERE rowid = (SELECT max(rowid) FROM data)
来源:https://stackoverflow.com/questions/12976670/fmdb-lastinsertrowid-always-0