Skip to content

Instantly share code, notes, and snippets.

@ciryon
Created August 26, 2010 19:14
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 ciryon/552028 to your computer and use it in GitHub Desktop.
Save ciryon/552028 to your computer and use it in GitHub Desktop.
-(NSArray*) openDatabaseWithSql:(NSString*)statement {
// Open the database. The database was prepared outside the application.
if (sqlite3_open([self.dbPath UTF8String], &database) == SQLITE_OK) {
// Get the primary key for all books.
const char *sql = [statement cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *statement;
// Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
// The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
NSLog(@"Processing results...");
NSMutableArray* array = [NSMutableArray array];
// We "step" through the results - once for each row.
while (sqlite3_step(statement) == SQLITE_ROW) {
int primaryKey = sqlite3_column_int(statement, 0);
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
CWWineObject* obj = [[CWWineObject alloc] init];
char* infoChars = (char *)sqlite3_column_text(statement, 2);
if (infoChars!=nil) {
NSString *info = [NSString stringWithUTF8String:infoChars];
obj.info = info;
}
obj.idNumber = primaryKey;
obj.name = name;
[array addObject:obj];
[obj release];
}
return array;
}
else {
NSLog(@"Error processing query: %s",sql);
NSLog(@"Database error message '%s'.", sqlite3_errmsg(database));
}
// "Finalize" the statement - releases the resources associated with the statement.
NSLog(@"Finalizing db...");
sqlite3_finalize(statement);
} else {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment