• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
FMDB - SLC-Cocoaheads
 

FMDB - SLC-Cocoaheads

on

  • 1,868 views

Short intro to FMDB, an Objective-C API or SQLite.

Short intro to FMDB, an Objective-C API or SQLite.

Statistics

Views

Total Views
1,868
Views on SlideShare
1,736
Embed Views
132

Actions

Likes
0
Downloads
0
Comments
0

1 Embed 132

http://www.stevensonsoftware.com 132

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    FMDB - SLC-Cocoaheads FMDB - SLC-Cocoaheads Presentation Transcript

    • FMDB
      • SLC Cocoaheads, November 2011
      • @dnstevenson
    •  
    •  
    • - ( NSMutableArray *) getStates{ NSMutableArray *states = [[ NSMutableArray alloc ] init ]; NSString *query = @"SELECT id, name, latitude, longitude FROM states" ; sqlite3_stmt *statement; int result = ( sqlite3_prepare_v2 ( database , [query UTF8String ], - 1 , &statement, nil )); if (result == SQLITE_OK ) { while ( sqlite3_step (statement) == SQLITE_ROW ) { State *state = [[ State alloc ] initWithId : sqlite3_column_int (statement, 0 ) withName :[ self checkForNull :( char *) sqlite3_column_text (statement, 1 )] withLatitude :[ self checkForNull :( char *) sqlite3_column_text (statement, 2 )] withLongitude :[ self checkForNull :( char *) sqlite3_column_text (statement, 3 )]]; [states addObject :state]; [state release ]; } sqlite3_finalize (statement); } return states; }
    • - ( NSMutableArray *) getStates { NSMutableArray *states = [[ NSMutableArray alloc ] init ]; NSString *query = @"SELECT id, name, latitude, longitude FROM states" ; FMResultSet *rs = [db executeQuery :query]; while ([rs next ]) { State *state = [[ State alloc ] initWithId :[rs intForColumnIndex : 0 ] withName :[rs stringForColumnIndex : 1 ] withLatitude :[rs stringForColumnIndex : 2 ] withLongitude :[rs stringForColumnIndex : 3 ]]; [states addObject :state]; [state release ]; } [rs close ]; return states; }
    • FMDB
      • Makes working with SQLite C APIs bearable
      • It’s not an ORM framework
      • Works on iOS and Mac
    • Do This [db executeUpdate : @"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" , @"hi'" , // look! I put in a ', and I'm not escaping it! @"number 10" , [ NSNumber numberWithInt :i], [ NSDate date ], [ NSNumber numberWithFloat : 2.2f ]];
    • Not This char *errorMsg; char *update = "INSERT INTO favorites (object_id) VALUES (?);" ; sqlite3_stmt *stmt; if ( sqlite3_prepare_v2 ( database , update, - 1 , &stmt, nil ) == SQLITE_OK ) { sqlite3_bind_int (stmt, 1 , objectID); } if ( sqlite3_step (stmt) != SQLITE_DONE ) { NSAssert1 ( 0 , @"Error updating table: %s" , &errorMsg); } sqlite3_finalize (stmt);
    •  
    • Baby Steps
      • Open Database:
        • FMDatabase *db = [ FMDatabase databaseWithPath : @"/tmp/tmp.db" ]
      • Do Something
        • [db executeUpdate : @"create table test (a text, b text, c integer, d double, e double)" ];
        • FMResultSet *rs = [db executeQuery : @"select rowid,* from test where a = ?" , @"hi'" ];
        • NSString *a = [rs stringForColumnIndex : 0 ];
    • First Step
      • Need to copy db from bundle to disk
        • - ( NSString *) dbFilePath {
      • // Check if the database already exists and if not, copy it over
      • NSFileManager *fileManager = [ NSFileManager defaultManager ];
      • NSArray *paths = NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory , NSUserDomainMask , YES );
      • NSString *documentsDirectory = [paths objectAtIndex : 0 ];
      • NSString *dbFile = [documentsDirectory stringByAppendingPathComponent : @"user_data.sql3" ];
      • NSError *error;
      • if ([fileManager fileExistsAtPath :dbFile] == NO ) {
      • NSString *pathToDefaultDB = [[ NSBundle mainBundle ] pathForResource : @"user_data" ofType : @"sql3" ];
      • if ([fileManager copyItemAtPath :pathToDefaultDB toPath :dbFile error :&error] == NO ) {
      • NSAssert1 ( 0 , @"Failed to copy data with error message '%@'." , [error localizedDescription]);
      • }
      • }
      • return dbFile;
      • }
    • Next Steps
      • Now you have a good path for:
        • FMDatabase *db = [ FMDatabase databaseWithPath :[ self dbFilePath ]];
      • Open the db:
        • [db open ];
    • Selecting Records FMResultSet *rs = [db executeQuery : @"select * from test where a = ?" , @"hi’" ]; while ([rs next ]) { NSLog ( @"%d %@ %@ %f" , [rs intForColumn : @"c" ], [rs stringForColumn : @"b" ], [rs dateForColumn : @"d" ], [rs doubleForColumn : @"e" ]); } [rs close ]; Note - the parameters passed into executeQuery are quote-safe (escaped)
    • Inserting Records int i = 0 ; while (i++ < 20 ) { [db executeUpdate : @&quot;insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)&quot; , @&quot;hi&quot; , [ NSString stringWithFormat : @&quot;number %d&quot; , i], [ NSNumber numberWithInt :i], [ NSDate date ], [ NSNumber numberWithFloat : 2.2f ]]; }
    • Reading Results
      • while ([rs next ]) {}
      • [rs intForColumnIndex : 0 ]
      • [rs stringForColumnIndex : 1 ]
      • [rs stringForColumn : @&quot;scientific_name&quot; ];
      • [rs doubleForColumnIndex : 1 ];
      • [rs dataForColumnIndex : 1 ];
      • [rs boolForColumnIndex : 1 ];
      • [rs longForColumnIndex : 0 ];
      • [rs objectForColumnIndex : 1 ];
      • [rs columnIndexIsNull : 1 ];
      • [rs close ];
    • Transactions
      • [db beginTransaction ];
          • << some insertions >>
      • [db commit ];
      Checking For Errors if ([db hadError ]) { NSLog ( @&quot;Err %d: %@&quot; , [db lastErrorCode ], [db lastErrorMessage ]); }
    • DEMO
    •  
    • More Info
      • FMDB - https://github.com/ccgus/fmdb
        • fmdb.m includes lots of examples
      • Demo Code on GitHub - https://github.com/dnstevenson/US-Landmarks
      • Ask Me for Help on Twitter: @dnstevenson