user825835
user825835

Reputation:

Retrieve count from SQLite statement in Objective-C

Presently I am using the following code, but how do I retrieve the count after the statement is executed to see whether or not the table contains data?

NSString *sql2 = @"SELECT COUNT( * ) FROM myTable";
sqlite3_stmt *stmt2 = [Cn OpenSQL:[sql2 UTF8String]];

if (stmt2 != nil) 
{
    if(sqlite3_step(stmt2)){
    NSLog(@"success")
    }
    else NSLog(@"err2: %@",sql2);
}

Upvotes: 1

Views: 3197

Answers (2)

Prabhat Kasera
Prabhat Kasera

Reputation: 1149

NSInteger count = sqlite3_column_int(statement, 0); 
// value of count will give you the answer

If count == 0, then there is no data.

If count > 0, then there is a tuple available in table.

Upvotes: 2

iMash
iMash

Reputation: 1188

NSString *sql2 = SELECT COUNT(*) FROM `myTable`;

If the result is 0 that means table is empty.

if (sqlite3_open([self.dataBasePath UTF8String], &articlesDB) == SQLITE_OK)
    {
        const char* sqlStatement = "SELECT COUNT(*) FROM MYTABLE";
        sqlite3_stmt *statement;

        if( sqlite3_prepare_v2(articlesDB, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
        {
            //Loop through all the returned rows (should be just one)
            while( sqlite3_step(statement) == SQLITE_ROW )
            {
                NSInteger count = sqlite3_column_int(statement, 0);
                NSLog(@"Rowcount is %d",count);
            }
        }
        else
        {
            NSLog( @"Failed from sqlite3_prepare_v2. Error is:  %s", sqlite3_errmsg(articlesDB) );
        }

        // Finalize and close database.
        sqlite3_finalize(statement);
        sqlite3_close(articlesDB);
    }

Upvotes: 2

Related Questions