Rahul
Rahul

Reputation: 509

Find Maximum Value in a column from sqlite database

I Am using following code for getting maximum value in column

Column no 11 (means 10 no, in the code) Column Name uniqueColumnSNo Data type of Column -integer.

I am confused with syntax used by dbhanlder.

Here is the code. Just let me know , HOW I WILL ACHIEVE MAXIMUM VALUE TO BE RETURNED from the specified column. Help. Thanks in Advance.

+(int)getMaxColumnSNo {

NSInteger favid;
int count=0;
sqlite3 *database;
NSString *dbpath;
dbpath = [dbhandler dataFilePath:DbName]; 
if (sqlite3_open([dbpath UTF8String], &database) == SQLITE_OK)
{
    NSString *selectSql = [NSString stringWithFormat:@"SELECT max(uniqueColumnSNo) FROM CustomerFields"];
    sqlite3_stmt *statement;
    if (sqlite3_prepare_v2(database, [selectSql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK)
    {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            //[result addObject:[[NSMutableDictionary alloc] init]];
            favid=(NSInteger)sqlite3_column_int64(statement,10);
            //favid =  [[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 10)] intValue];
            count++;

        }
        sqlite3_finalize(statement);
    }
    else
    {
        NSLog(@"Sql Preparing Error");
    }
    sqlite3_close(database);
}
else
{
    NSLog(@"Database not opening");
}
int i;
if (count!=0) {
i=favid ;

}
else {
    i=1;
}

return i;
//return favid;

}

Upvotes: 2

Views: 2132

Answers (1)

Nick Shaw
Nick Shaw

Reputation: 2113

You need:

sqlite3_column_int64( statement, 0 );

The column number parameter is the index of the result set, not of the original table column number. Your only column in the result set is max(uniqueColumnSNo), thus this is column index number 0.

Upvotes: 2

Related Questions