Skip to content

Instantly share code, notes, and snippets.

Created September 19, 2010 14:34
Show Gist options
  • Save anonymous/586811 to your computer and use it in GitHub Desktop.
Save anonymous/586811 to your computer and use it in GitHub Desktop.
#import "SqlDB.h"
@implementation SqlDB
@synthesize returnedValues;
-(void)createDB
{
if(sqlite3_open([[self filePath] UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
}
char *errorMsg;
NSString *createSQL = @"CREATE TABLE IF NOT EXISTS ENTRY (entryID INTEGER PRIMARY KEY AUTOINCREMENT, entryDate TEXT, entryTitle TEXT, entryContext TEXT, entryImage TEXT)";
if(sqlite3_exec (database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK)
{
NSAssert1(0,@"Error creating table: %s", errorMsg);
}
sqlite3_close(database);
}
-(NSString *)filePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:dbFilename];
}
-(void)openDB
{
if(sqlite3_open([[self filePath] UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
}
}
-(void)sqlInsert:(NSArray *)insertValues
{
[self openDB];
NSString *todayDate = [insertValues objectAtIndex:0];
NSString *addTitle = [insertValues objectAtIndex:1];
NSString *addContext = [insertValues objectAtIndex:2];
NSString *addImageName = [insertValues objectAtIndex:3];
NSString *insert = [[NSString alloc] initWithFormat:@"INSERT INTO entry (entryDate, entryTitle, entryContext, entryImage) VALUES ('%@', '%@', '%@', '%@');", todayDate, addTitle, addContext, addImageName];
char *errorMsg;
if(sqlite3_exec(database, [insert UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK)
{
NSAssert1(0,@"Error updating tables: %s", errorMsg);
}
[insert release];
sqlite3_close(database);
}
-(NSArray *)sqlSelectAll
{
[self openDB];
NSString *query = @"SELECT entryTitle, entryContext, entryImage FROM ENTRY ORDER BY entryDate DESC LIMIT 1";
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
char *title = (char *)sqlite3_column_text(statement, 0);
char *context = (char *)sqlite3_column_text(statement, 1);
char *image = (char *)sqlite3_column_text(statement, 2);
NSString *readTitle = [[NSString alloc] initWithUTF8String: title];
NSString *readContext = [[NSString alloc] initWithUTF8String: context];
NSString *readImage = [[NSString alloc] initWithUTF8String: image];
returnedValues = [[NSArray alloc] initWithObjects: readTitle, readContext, readImage, nil];
[readTitle release];
[readContext release];
[readImage release];
}
}
return returnedValues;
if(statement) {
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
- (void)dealloc {
[returnedValues release];
[super dealloc];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment