Skip to content

Instantly share code, notes, and snippets.

@yajamon
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yajamon/f1ecb56738570f2e7f59 to your computer and use it in GitHub Desktop.
Save yajamon/f1ecb56738570f2e7f59 to your computer and use it in GitHub Desktop.
sqlite3 drawing row method in Objective-C.
#import <sqlite3.h>
@interface SQLExecuter ()
@property (nonatomic) NSDictionary *database;
@property (nonatomic) sqlite3_stmt *stmt;
@end
@implementation SQLExecuter
-(NSArray *)drawAllRows {
/* prepare success, bind success */
NSMutableArray *rows = [@[] mutableCopy];
while(sqlite3_step(self.stmt) == SQLITE_ROW) {
[rows addObject:[self drawRow]];
}
return [rows copy];
}
-(NSDictionary *)drawRow {
/* prepare success, bind success, step success */
NSMutableDictionary *row = [@{} mutableCopy];
NSInteger columnCount = sqlite3_column_count(self.stmt);
for (NSInteger index=0; index < columnCount; ++index) {
NSString *columnName = [self drawColumnNameByIndex:index];
row[columnName] = [self drawValueByIndex:index];
}
return [row copy];
}
-(NSString *)drawColumnNameByIndex:(NSInteger)index {
return [NSString stringWithUTF8String:sqlite3_column_name(self.stmt, (int)index)];
}
-(id)drawValueByIndex:(NSInteger)index {
NSInteger columnTypeKey = sqlite3_column_type(self.stmt, (int)index);
return [self drawValueByIndex:index andColumnType:columnTypeKey];
}
-(id)drawValueByIndex:(NSInteger)index andColumnType:(NSInteger)type {
if (type == SQLITE_INTEGER){
NSInteger value = sqlite3_column_int64(self.stmt, (int)index);
return @(value);
}
if (type == SQLITE_FLOAT){
double value = sqlite3_column_double(self.stmt, (int)index);
return @(value);
}
if (type == SQLITE_TEXT){
NSString *value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(self.stmt, (int)index)];
return value;
}
if (type == SQLITE_BLOB){
NSInteger length = sqlite3_column_bytes(self.stmt, (int)index);
NSData *value = [[NSData alloc] initWithBytes:sqlite3_column_blob(self.stmt, index) length:length];
return value;
}
if (type == SQLITE_NULL){
return nil;
}
return nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment