我在iPhone上使用iOS4中的SQLite,但我的更新语句所做的更改未保存。起初认为可能退出应用程序可能会以某种方式删除数据库,但它们甚至在同一会话期间都没有持久化。初始化我的数据库的代码是(使用FMDB):
-(SQLiteDal*) init {
pool = [[NSAutoreleasePool alloc] init];
self = [super init];
if(self != nil){
// Setup some globals
NSString *databaseName = [self getDbPath];
NSLog([NSString stringWithFormat:@"db path: %@", databaseName]);
db = (FMDatabase *)[FMDatabase databaseWithPath:databaseName];
if (![db open]) {
NSLog(@"Could not open db.");
[pool release];
return 0;
}
}
//[self checkAndCreateDatabase];
return self;
}
#pragma mark DB Maintenance
-(NSString *)getDbPath {
NSString *databaseName = @"myapp.db";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databaseName = [documentsDir stringByAppendingPathComponent:databaseName];
return databaseName;
}
调用这两个方法 来创建数据库,然后插入我调用的表:
[db executeQuery:@"INSERT INTO MyTable (Name, Description, Area, Price, ID) VALUES (?,?,?,?,?)",
f.Name,
f.description,
f.area,
f.price,
f.id];
问题是,当我使用下面的陈述来阅读MyTable
时,我从未得到任何回报:
FMResultSet *rs = [db executeQuery:@"SELECT * FROM MyTable WHERE ID = ?", id];
while ([rs next]) {
//.. this is never called
据我所知,我并没有遗漏任何东西,而且数据库似乎处于可写的位置。
答案 0 :(得分:5)
插入时,您需要拨打executeUpdate
而不是executeQuery
。您还应该拨打beginTransaction
然后commit
,如下所示:
[_dbPointer beginTransaction];
BOOL isInserted = [_dbPointer executeUpdate:[NSString stringWithFormat:@"INSERT INTO MyTable (Name, Description, Area, Price, ID) VALUES(?,?,?,?,?);", f.Name,
f.description,
f.area,
f.price,
f.id]];
[_dbPointer commit];