sqlite sum()进入nsinteger

时间:2012-08-30 22:35:05

标签: objective-c xcode fmdb nsinteger

我想构建一个函数,它接受名为hours的列中所有行的总和。它应该返回一个整数值,我将用它来乘以另一个数字。

-(NSInteger)calculateTotal{

FMDatabase *dbHandler = [FMDatabase databaseWithPath:[Utility getDatabasePath]];

[dbHander open];

FMResultSet *results = [dbHandler executeQuery:@"SELECT SUM(hours) FROM inputs"];

NSInteger totalHours;
while ([results next]) {
    totalHours = [results intForColumn:@"hours"];
}

return totalHours;
}

但是它不起作用,它返回0,并且它附带一个警告,说没有名为“小时”的列

2 个答案:

答案 0 :(得分:0)

我认为大多数数据库引擎会在最外面的聚合函数SUM之后命名查询结果中的列。

尝试将您的查询更改为SELECT SUM(hours) AS hours FROM inputs。 (或者,如果您查询Oracle,那么您不幸的是,查询没有AS。)

答案 1 :(得分:0)

以下代码可以使用:

-(NSInteger)calculateTotal
{
  FMDatabase *dbHandler = [FMDatabase databaseWithPath:[Utility getDatabasePath]];

  if(![dbHander open])
  {
        NSLog(@"Could not open DB, try again");
        return -1; //return some value that tells you that there was an error
  }

  FMResultSet *results = [dbHandler executeQuery:@"SELECT SUM(hours) AS sum_hours FROM inputs"];

  NSInteger totalHours = -1;
  while ([results next]) {
      totalHours = [results intForColumn:@"sum_hours"];
  }

  [results close];
  [dbHandler close];
  return totalHours;
}