views:

1019

answers:

2
- init
{
    if(![super init]) return nil;

    //the database is stored in the application bundle.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *path = [documentsDirectory stringByAppendingFormat:@"/base.sqlite"];
    NSLog(@"%@",path);
    db = [FMDatabase databaseWithPath:path];
    [db setLogsErrors:YES];

    if (![db open]) { 
        NSLog(@"Could not open db."); 
        return 0; 
    } else { 
     NSLog(@"DB Open...."); 
    } 

    FMResultSet *rs = [db executeQuery:@"SELECT * FROM settings"]; 

    return self; 
}

that's the code i use for trying to access the data from settings. but this gives an error (and i can assure you that there is a settings table ! )

here is a dump from the terminal

BEGIN TRANSACTION;
CREATE TABLE About (id integer PRIMARY KEY AUTOINCREMENT,key varchar UNIQUE,value text);
DELETE FROM sqlite_sequence;
CREATE TABLE settings (version integer,updated timestamp,owner varchar);
INSERT INTO "settings" VALUES(1,'2009-05-11 14:29:07','boulevart');
COMMIT;

and the error:

2009-05-11 16:14:19.799 SummerGuide[9892:20b] /Users/andyjacobs/Library/Application Support/iPhone Simulator/User/Applications/762630F5-78CB-41A4-85C2-964316ACFE1D/Documents/base.sqlite
2009-05-11 16:14:19.801 SummerGuide[9892:20b] DB Open....
2009-05-11 16:14:19.804 SummerGuide[9892:20b] DB Error: 1 "no such table: settings"
2009-05-11 16:14:19.804 SummerGuide[9892:20b] DB Query: SELECT * FROM settings

the strange thing is if i change my path to for example /baseeeeee.sqlite (which ain't no file ) it still says "DB Open...."

I just added an existing sqlite file (base.sqlite) to my recourse folder and added the sqlite3 lib to my frameworks.

+1  A: 

To get the path to your file in the app bundle, use this:

[[NSBundle mainBundle] pathForResource:@"base" ofType:@"sqlite"];

To actually open the database, you may have to copy it to the Documents directory first, because trying to modify a file in your app bundle is bad news.

Chris Lundie
Do you have to copy it to the documents directory if you want to insert or update some records ?
Andy Jacobs
Yes. The reason is that your application's code signature is tied to a secure hash of everything in the application bundle. If you modify something in the bundle you'll make that code signature invalid; this would (I imagine, not having explicitly tried it) make your app fail to launch, since the code signature would now be invalid.
Jim Dovey
A: 

I want to actually use the database in the bundle. I don't want to copy teh file to documents or edit it. It's a read only database. Your code snippit specifies the file, but I'm having difficulties working out how to open it for the array.

Any advice or code lines?