【问题标题】:sqlite sum() into nsintegersqlite sum() 到 nsinteger
【发布时间】:2012-08-30 22:35:04
【问题描述】:

我想构建一个函数,它获取名为 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,并带有警告说没有名为“小时”的列

【问题讨论】:

  • 您是否尝试查看您的数据库并查看是否有一个名为“小时”的列?
  • 是的,我有一个名为小时的列。但这不应该有效吗?

标签: objective-c xcode fmdb nsinteger


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    以下代码将起作用:

    -(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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 2021-11-17
      相关资源
      最近更新 更多