使用SQLite数据库存储数据(3)查询结果集

查询结果集

结果集的查询,需要用到SQL Statement对象。Statement对象表示一条SQL语句,可以理解为prepared statement或者compiled statement。一般使用sqlite3_prepare_v2() 函数创建Statement对象。

头文件中定义了2个成员变量:
sqlite3 *noteDB;
NSString *databasePath;

示例代码如下所示:

- (void) initializeDataToDisplay{
self.noteArray = [[NSMutableArray alloc] init];

const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;

if(sqlite3_open(dbpath,&noteDB) == SQLITE_OK){
NSString *querySql = [NSString stringWithFormat:@"SELECT id, whattime, address, what, who, note FROM Notebook"];
const char *query_stmt = [querySql UTF8String];

if(sqlite3_prepare_v2(noteDB, query_stmt, -1, &statement, NULL) == SQLITE_OK){
while (sqlite3_step(statement) == SQLITE_ROW) {
NotebookInfo *notebookInfo = [[NotebookInfo alloc] init];
notebookInfo.pk_id =sqlite3_column_int(statement, 0);
notebookInfo.whattime = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,1)];
notebookInfo.what = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
[noteArray addObject:notebookInfo];
}
} else {
NSLog(@"Problem with prepare statement: %s", sqlite3_errmsg(noteDB));
}

// 销毁Statement对象
sqlite3_finalize(statement);
}
}

将查询的结果存放在noteArray数组中,然后由Table View 表视图显示数据记录。

关于表视图的具体使用,可以参考表视图的教程

原文地址:https://www.cnblogs.com/tuncaysanli/p/2727955.html