1

我想构建一个函数,它获取名为小时的列中所有行的总和。然后它应该返回一个整数值,我将用它与另一个数字相乘。

-(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,并带有警告说没有名为“小时”的列

4

2 回答 2

0

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

尝试将您的查询更改为SELECT SUM(hours) AS hours FROM inputs. (或者,如果你正在查询 Oracle,你这个倒霉的人,查询没有AS.)

于 2012-08-31T01:09:29.390 回答
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;
}
于 2012-08-31T05:46:09.883 回答