如何迭代sqlite_step结果

时间:2013-04-10 16:48:47

标签: ios sqlite

有人可以如此善良地填写下面几条缺失的代码。我正在努力使用sqlite3_step执行sqlite语句,遍历每行结果并将数据放入可用格式。

以下是创建数据库的代码(数据库只有两个列)

// Check if database is setup, if not create it
NSString *documents_directory;
NSArray *directory_path;

// Get the documents directory
directory_path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

documents_directory = [directory_path objectAtIndex:0];

// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [documents_directory stringByAppendingPathComponent:  @"weights.db"]];

NSFileManager *file_manager = [NSFileManager defaultManager];

// Create database if it doesn't already exist
if([file_manager fileExistsAtPath: databasePath ] == NO){
    const char *database_path = [databasePath UTF8String];

    if(sqlite3_open(database_path, &contactDB) == SQLITE_OK){
        char *error_message;
        const char *sql_statement = "CREATE TABLE IF NOT EXISTS RECORDED_WEIGHTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, WEIGHT TEXT, TIME TEXT)";

        if(sqlite3_exec(contactDB, sql_statement, NULL, NULL, &error_message) != SQLITE_OK){
            status.text = @"Failed to create table";                
        }
        sqlite3_close(contactDB);

    }else{
        status.text = @"Failed to open/create database";
    }
}

以下是我要完成的代码;

// Get info from database and load it.
const char *database_path = [databasePath UTF8String];
sqlite3_stmt *statement;

if(sqlite3_open(database_path, &contactDB) == SQLITE_OK){

    NSString *SQLquery = [NSString stringWithFormat:@"SELECT * FROM RECORDED_WEIGHTS ORDER BY TIME DESC"];

    const char *query_statement = [SQLquery UTF8String];


    if(sqlite3_prepare_v2(contactDB, query_statement, -1, &statement, NULL) == SQLITE_OK){

        // Please help me execute statement and get results into useable format here.




    }

    sqlite3_finalize(statement);

}
sqlite3_close(contactDB);

提前致谢。

1 个答案:

答案 0 :(得分:0)

你想做这样的事情:

while(sqlite3_step(statement) == SQLITE_ROW) 
{
   // int value
   int intValue = sqlite3_column_int(statement,fieldIndex);

   // string value
   NSString* stringValue;
   if (sqlite3_column_type(dbps, fieldIndex) != SQLITE_NULL) 
   {
       const char *c = (const char *)sqlite3_column_text(dbps, fieldIndex);
       if (c) 
       {
          stringValue = @(c);
       }
   }

        ... etc...
}

查看不同列类型的文档。您还可以查看不同的objective-c包装器,以了解如何访问数据库。