如何在iOS中通过sqlite查询接收组的数据?

时间:2013-07-25 14:38:26

标签: ios objective-c sqlite

我想通过查询获取我的组的数据并将它们加载到文本字段中。 这是我的桌子 整数ID 姓名文字 持续时间真实 时间真实 名称列中的名称很少 我尝试为每个名称调用方法,但它导致插入失败。

我想收到此查询并在特定标签上加载结果:我不知道如何获得响应

SELECT  Name,SUM (time) FROM  cost GROUP BY Name;

有我当前的代码

 NSString *docsDir;
NSArray *dirPaths;

 double totaltime = 1.0;

// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];

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


NSString *queryString=@"SELECT SUM(DURATION) AS TOTAL FROM RECORDS";
sqlite3_stmt    *statement;

if(sqlite3_open([databasePath UTF8String], &myDatabase) == SQLITE_OK) {

    if(sqlite3_prepare_v2(myDatabase, [queryString UTF8String], -1, &statement, nil) == SQLITE_OK){
        while (sqlite3_step(statement) == SQLITE_ROW) {
             totaltime =  sqlite3_column_double(statement, 0);
            NSLog(@"The sum is  %f ", totaltime);
        }
    }
}
integer_t intotal=totaltime;
NSString* total=[NSString stringWithFormat:@"%d min",intotal];
totaltimefield.text=total;

1 个答案:

答案 0 :(得分:1)

这完全涵盖了nicely in the documentation,但简而言之,一旦您将SQL更新为两列:

const unsigned char* name = sqlite3_column_text(statement, 0);
double totaltime =  sqlite3_column_double(statement, 1);
NSLog(@"The sum for %s is  %f ", name, totaltime);

sqlite3_column_x函数中的第二个参数是列号。