Your SlideShare is downloading. ×
FMDB - SLC-Cocoaheads
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

FMDB - SLC-Cocoaheads

1,565
views

Published on

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

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

Published in: Technology

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,565
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. FMDB
    • SLC Cocoaheads, November 2011
    • @dnstevenson
  • 2.  
  • 3.  
  • 4. - ( 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; }
  • 5. - ( 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; }
  • 6. FMDB
    • Makes working with SQLite C APIs bearable
    • It’s not an ORM framework
    • Works on iOS and Mac
  • 7. 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 ]];
  • 8. 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);
  • 9.  
  • 10. 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 ];
  • 11. 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;
    • }
  • 12. Next Steps
    • Now you have a good path for:
      • FMDatabase *db = [ FMDatabase databaseWithPath :[ self dbFilePath ]];
    • Open the db:
      • [db open ];
  • 13. 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)
  • 14. 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 ]]; }
  • 15. 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 ];
  • 16. Transactions
    • [db beginTransaction ];
        • << some insertions >>
    • [db commit ];
    Checking For Errors if ([db hadError ]) { NSLog ( @&quot;Err %d: %@&quot; , [db lastErrorCode ], [db lastErrorMessage ]); }
  • 17. DEMO
  • 18.  
  • 19. 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

×