I'm checking and creating a database using the following function:
-(void) checkAndCreateDatabase
{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL dbExists;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
dbExists = [fileManager fileExistsAtPath:_databasePath];
// If the database already exists then return without doing anything
if(dbExists)
{
//sqlite3_open([self.databasePath UTF8String], &_database);
NSLog(@"DB DOES EXIST");
return;
}
NSLog(@"DB DOES NOT YET EXIST");
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];
}
The database name and path are properly set here, in the init function for my Search class:
- (id)init
{
if ((self = [super init]))
{
_databaseName = DB_NAME;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
_databasePath = [documentsDir stringByAppendingPathComponent:_databaseName];
if (sqlite3_open([_databasePath UTF8String], &_database) != SQLITE_OK)
{
[[[UIAlertView alloc]initWithTitle:@"Missing"
message:@"Database file not found"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil]show];
}
}
return self;
}
Then, I query the database using:
-(void)search:(NSString *)searchTerm
{
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
/* Begin Database Work */
if(sqlite3_open(dbpath, &_database) == SQLITE_OK)
{
NSString *querySQL = @"SELECT * FROM types";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_database, query_stmt, -1, &statement, NULL))
{
if(sqlite3_step(statement) == SQLITE_ROW)
{
NSLog([[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement,1)]);
}
else
{
NSLog(@"nope2: query = ");
printf(query_stmt);
}
}
else
{
NSLog(@"nope1");
}
}
}
I'm always getting "nope2" returned, which seems to imply that no results are returned. When I run the exact same query on the database in SQLite directly, however, I get the results I expect. This leads me to believe that I'm doing something wrong in the code. What looks wrong here?