Last Updated: February 25, 2016
·
808
· brainfree

Executing SQL, returning results to a block

This is a handy set of code to execute sql with the sqlite3 library and be able to deal with the results as a block instead of through callback functions.

typedef int (^SQLCallbackBlock)(int argc, char** argv, char** columnName);

- (void)executeSQLCommand:(NSString*)sqlCommand connection:(IAAppSyncSQLConnection)connection callbackBlock:(SQLCallbackBlock)callbackBlock
{
    char *errMsg;

    sqlite3_exec( connection.database, [sqlCommand UTF8String], sqlPassBlockCallback, (__bridge void*)callbackBlock, &errMsg );

    if (errMsg) {
        NSLog(@"SQL: %@", sqlCommand);
        NSLog(@"SQL Error: %s", errMsg);
    }
}

int sqlPassBlockCallback( void* userInfo, int argc, char** argv, char** columnName )
{
    SQLCallbackBlock callBlock = (__bridge SQLCallbackBlock)userInfo;
    return callBlock( argc, argv, columnName );
}

Example use:

sqlCommand = [NSString stringWithFormat:@"SELECT name FROM sqlite_master WHERE type='table' AND name='%@'", entity.name];

__block BOOL tableExists = NO;

[self executeSQLCommand:sqlCommand connection:db callbackBlock:^int(int argc, char **argv, char **columnName) {
    tableExists = YES;
    return SQLITE_OK;
}];