我通過FMDB管理SQLite數據。FMDB:提前輸入數據
在這個應用程序中,我想提前輸入數據,所以我先將dbfile sample.db
提前terminal
和Lita
,複製並導入到項目中。
問題是你不能更新數據庫。
即使調用saveData
,列title
爲空。
我該如何解決更新數據庫?
·在sample.db
,有一個表events
。
·表events
模式爲(id INTEGER PRIMARY KEY AUTOINCREMENT, day TEXT, title TEXT, time INTEGER);
·您將數據Event
添加到表events
。
現在,您調用方法saveData
並將"test"
放入events
。
Event.h
@interface Event : NSObject
@property (nonatomic, assign) NSInteger eventId;
@property (nonatomic, copy) NSString* day;
@property (nonatomic, copy) NSString* title;
@property (nonatomic, assign) NSInteger time;
DetailViewController.m
- (void)saveData:(id)sender
{
Event* newEvent = [[Event alloc]init];
newEvent.title = @「test";
[self.delegate editEventDidFinish:self.event newEvent:newEvent];
@end
MasterViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.daoEvents = [[DaoEvents alloc] init];
}
- (void)editEventDidFinish:(Event *)oldEvent newEvent:(Event *)newEvent
{
[self.daoEvents update:newEvent];
[self.navigationController popViewControllerAnimated:YES];
}
- (void)removeOldEnent:(Event*)oldEvent
{
[self.daoEvents remove:oldEvent.eventId];
}
DaoEvents.m
#define DB_FILE_NAME @「sample.db"
#define SQL_UPDATE @"UPDATE events SET day = ?, title = ?, time = ? WHERE id = ?;」
#define SQL_DELETE @"DELETE FROM events WHERE id = ?;"
- (FMDatabase *)dbConnect
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* dir = [paths objectAtIndex:0];
return [FMDatabase databaseWithPath:[dir stringByAppendingPathComponent:DB_FILE_NAME]];
}
- (BOOL)update:(Event *)event
{
FMDatabase* db = [self dbConnect];
[db open];
BOOL success = [db executeUpdate:SQL_UPDATE, event.day, event.title, [NSNumber numberWithInt:event.time],[NSNumber numberWithInteger:event.eventId]];
[db close];
NSLog(@"%@", event.title); //correctly outputs 「test"
return success;
}
- (BOOL)remove:(NSInteger)eventId
{
FMDatabase* db = [self dbConnect];
[db open];
BOOL isSucceeded = [db executeUpdate:SQL_DELETE, [NSNumber numberWithInteger:eventId]];
[db close];
return isSucceeded;
}
我該如何解決更新數據庫?
謝謝。
在您嘗試執行更新之前,您正在刪除記錄。刪除的記錄是否與您正在嘗試更新的'id'一致?如果是這樣,如果你真的想更新它,刪除'DELETE'。如果你打算刪除並添加一條新記錄,那麼執行'INSERT'而不是'UPDATE'。 – Rob