Search code examples
iosiphonesqlitefmdb

Select data from SQLite


Here is my code, and error is visible also:

enter image description here

In SQLite Manager from Mozzila Firefox - all queries work fine which means that DB is correct

Maybe someone can piont me out what is wrong with my code?

EDIT:

My code:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"stories_db.sqlite"];

FMDatabase *db = [FMDatabase databaseWithPath:path];
//[db open];
if ([db open]==true)
{
    FMResultSet *resultsFavorite = [db executeQuery:@"SELECT count(*) from favorites"];
    while ([resultsFavorite next])
    {
        Pasaka *pasaka = [[Pasaka alloc]init];
        pasaka.title = [resultsFavorite stringForColumn:@"story_name"];
        pasaka.image = [resultsFavorite stringForColumn:@"image_path"];
        pasaka.movie = [resultsFavorite stringForColumn:@"video_path"];
        [favoriteMovieList addObject:pasaka];
    }

}

EDIT 2:

When i do this query:

FMResultSet *results = [db executeQuery:@"SELECT count(*) FROM sqlite_master"];

it doesn't show any errors.


Solution

  • You need to copy your database to your document folder first (also check if your sqlite file was properly added in the Copy Bundle Resources in Build Phases of your project setting):

    //Where your original database file is
    bundleDatabasePath = [[NSBundle mainBundle] pathForResource:@"stories_db" ofType:@"sqlite"];
    //Where you will copy it in order to be used
    documentDatabasePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingString:@"/stories_db.sqlite"];
    
    //Using the default file manager
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    //Copy empty database into document folder
    if (![fileManager copyItemAtPath:bundleDatabasePath toPath:databasePath error:&error]) {
        //Error
        NSLog(@"Could not copy the database into document folder. Error:%@", error);
    }
    
    //Use DB
    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];