1、导入SQLite库和头文件
#import <sqlite3.h>
2、打开数据库,如果在打开的时候遇到了问题,则关闭它并抛出一个断言错误。
sqlite3 * database;
if (sqlite3_open([[self dataFilePath] UTF8String], &database)
!= SQLITE_OK) {
sqlite3_close(database);
NSAssert(, @"Failed to open database");
}
3、确保有一个表来保存数据
NSString * createSQL = @"CREATE TABLE IF NOT EXISTS FIELDS "
"(ROW INTEGER PRIMARY KEY, FIELD_DATA TEXT);";
char * errorMsg;
if (sqlite3_exec (database, [createSQL UTF8String],
NULL, NULL, &errorMsg) != SQLITE_OK) {
sqlite3_close(database);
NSAssert(, @"Error creating table: %s", errorMsg);
}
4、加载数据
创建一个SELECT来从数据库请求所有行,并要求SQLite准备我们的SELECT。这里是告诉SQLite按行号排序各行,以便我们总是以相同顺序获取他们。否则SQLite会按内部存储顺序返回各行。
NSString * query = @"SELECT ROW, FIELD_DATA FROM FIELDS ORDER BY ROW";
sqlite3_stmt * statement;
if (sqlite3_prepare_v2(database, [query UTF8String],
-, &statement, nil) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW) {
int row = sqlite3_column_int(statement, );
char *rowData = (char *)sqlite3_column_text(statement, ); NSString *fieldValue = [[NSString alloc]
initWithUTF8String:rowData];
UITextField *field = self.lineFields[row];
field.text = fieldValue;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
5、applicationWillResignActive:方法首先会打开数据库,然后保存数据。
UIApplication * app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:app];
- (void)applicationWillResignActive:(NSNotification *)notification
{
sqlite3 * database;
if (sqlite3_open([[self dataFilePath] UTF8String], &database)
!= SQLITE_OK) {
sqlite3_close(database);
NSAssert(, @"Failed to open database");
}
for (int i = ; i < ; i++) {
UITextField *field = self.lineFields[i];
// Once again, inline string concatenation to the rescue:
char *update = "INSERT OR REPLACE INTO FIELDS (ROW, FIELD_DATA) "
"VALUES (?, ?);";
char * errorMsg = NULL;
sqlite3_stmt * stmt;
if (sqlite3_prepare_v2(database, update, -, &stmt, nil)
== SQLITE_OK) {
sqlite3_bind_int(stmt, , i);
sqlite3_bind_text(stmt, , [field.text UTF8String], -, NULL);
}
if (sqlite3_step(stmt) != SQLITE_DONE)
NSAssert(, @"Error updating table: %s", errorMsg);
sqlite3_finalize(stmt);
}
sqlite3_close(database);
}