简体   繁体   English

iOS SQLite 求和和检索数据

[英]iOS SQLite Sum and retrieve data

I have a SQLite database that I am creating in my iOS application.我在我的 iOS 应用程序中创建了一个 SQLite 数据库。 A series of numbers are being stored in this database.该数据库中存储了一系列数字。 I want to sum the entire column, and return the data to be displayed within the application.我想对整列求和,并返回要在应用程序中显示的数据。

Everything writing to the DB is working properly, but I am stuck trying to return the summed data.写入数据库的所有内容都正常工作,但我一直试图返回汇总数据。 Any help would be greatly appreciated.任何帮助将不胜感激。

-(void) dataReturn: (NSString *) tableNamed{
    NSString *myData = [NSString stringWithFormat:@"SELECT SUM(column1) AS data1 FROM myDB", tableNamed];

    sqlite3_stmt *statement;

    if(sqlite3_prepare_v2(db, [myData UTF8String], -1, &statement, nil) ==SQLITE_OK){
        while (sqlite3_step(statement) == SQLITE_ROW){

            int *field2 = (int *) sqlite3_column_int(statement, 1);

            NSString *myString =[[NSString alloc] initWithFormat:@"%@", field2];

        }
    }
}

Hello Nathan making a call as你好,内森打电话给

[self  dataReturn:@"Bill"]; 

to function至 function

-(void)dataReturn:(NSString *)tableName{

    sqlite3 *database;
    sqlite3_stmt *statement;

    NSString *queryString = [NSString stringWithFormat:@"SELECT SUM(price) AS TOTAL FROM %@", tableName];

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

        if(sqlite3_prepare_v2(database, [queryString UTF8String], -1, &statement, nil) == SQLITE_OK){
            while (sqlite3_step(statement) == SQLITE_ROW) {
                    int field1 =  sqlite3_column_int(statement, 0);
                    NSLog(@"The sum is  %d ", field1);
            }
        }
    }
}

will Fetch you desired data.将获取您想要的数据。 The schema for Table "Bill" is "CREATE TABLE Bill (price double,quantity INTEGER)".表“Bill”的架构是“CREATE TABLE Bill (price double,quantity INTEGER)”。 The result fetched will have columns indexed from "0" so we pass 0 for first column.获取的结果将具有从“0”索引的列,因此我们将 0 传递给第一列。 Hope you can take some hint from it.希望你能从中得到一些提示。 Cheers!!干杯!!

int field1 =  sqlite3_column_int(statement, 0);

From the sqlite3_column_int docs:来自sqlite3_column_int文档:

The leftmost column of the result set has the index 0.结果集的最左侧列的索引为 0。

Additionally, that function returns an int , not an int* .此外,该 function 返回一个int ,而不是一个int* Try:尝试:

int field2 = sqlite3_column_int(statement, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM