我有了一個學生實體數據庫:SQLite數據庫沒有更新
create table student (name varchar(20) not null,
surname varchar(20) not null,
studentId integer primary key);
在我的應用程序代理應用程序啓動時加載我從數據庫中所有的記錄,並將其顯示到表格視圖。
當應用程序委託接收器applicationWillResignActive事件時,它將所有元組保存到數據庫中。它只保存已添加的元組,所以沒有編輯元組的可能性,所以很好。
當應用程序委託收到applicationWillEnterForeground事件時,它從數據庫中讀取元組。
問題:這隻能在單個推出的application.Let的內線說,我通過Xcode中啓動應用程序,然後我進入我添加元素和background.Afterwards我重新輸入應用程序,它會在前臺,並且它成功加載所有的元組。
但是在應用程序的下一次啓動(從lldb中停止並再次啓動它)中,元組與第一次啓動之前的元組相同。
我創建了學生的實體包裝類,名爲學生,具有這些性質:
@property (nonatomic, copy, readwrite) NSString* name;
@property (nonatomic, copy , readwrite) NSString* surname;
@property (nonatomic, strong, readwrite) NSNumber* studentId;
@property (nonatomic, readwrite, getter= isNew) BOOL new;
我檢查字段不爲零,而且實體完整性不受侵犯。
我使用的唯一有意義的方法是這樣的:
- (NSString*) sqlInsertionString;
它創建插入tuple.Tested和工作所必需的字符串。
所以這就是我如何更新數據庫:
- (void) updateStudents : (NSMutableArray*) students
{
sqlite3* database;
sqlite3_stmt* statement;
BOOL needsFinalize=NO;
if(!databasePath)
{
NSBundle* bundle=[NSBundle mainBundle];
databasePath= [bundle pathForResource: @"test" ofType: @"db"];
}
if(sqlite3_open([databasePath UTF8String], &database)!=SQLITE_OK)
{
NSString* problem= [NSString stringWithFormat: @"%s",sqlite3_errmsg(database)];
@throw [NSException exceptionWithName: @"Failed to open the database" reason: problem userInfo: nil];
}
for(Student * s in students)
{
if(s.isNew)
{
NSString* sqlString= [s sqlInsertionString];
if(sqlite3_prepare_v2(database, [sqlString UTF8String], -1, &statement, NULL)!= SQLITE_OK)
{
@throw [NSException exceptionWithName: @"Problem performing the query" reason: @"Unknown" userInfo: nil];
}
if(sqlite3_step(statement)!=SQLITE_DONE)
{
@throw [NSException exceptionWithName: @"Problem performing the query" reason: @"Unknown" userInfo:nil];
}
sqlite3_reset(statement);
needsFinalize=YES;
}
}
if(needsFinalize && sqlite3_finalize(statement)!=SQLITE_OK)
{
@throw [NSException exceptionWithName: @"Failed to close the statement resource" reason: @"Unknown" userInfo:nil];
}
if(sqlite3_close(database)!= SQLITE_OK)
{
@throw [NSException exceptionWithName: @"Failed to close the database" reason: @"Unknown" userInfo: nil];
}
}
但它不會真正更新,只有在應用程序內它似乎被更新,但該文件始終保持不變。