Skip to content

iPhone, how to insert a record using fmdb

One of the easiest ways to perform transactions with a database with the iPhone is with the fmdb libraries. Its a few lines of code to do almost anything.

This is the primary documentation for fmdb

It’s pretty good and straight forward. But, I’ve had some problems today trying to insert a record. None of the usage code I found on the web seemed to be any different to the code I was using.

However, after inserting one field at a time I found my problem was due to using an integer where I needed to use NSNumber. So I thought I’d post the code I arrived at, maybe it will help someone else.

NSMutableString *strAmount = [NSMutableString stringWithString:txtAmount.text];
[strAmount replaceCharactersInRange: [strAmount rangeOfString: strCurrencySymbol]  withString:@""];

NSString *strRecurrance = [self.pickerRecurranceData objectAtIndex:intSelRecurrenceRow];
NSArray *parts = [strRecurrance componentsSeparatedByString: @" "];

NSNumber *numInterval = [NSNumber numberWithInt:[[parts objectAtIndex:0] intValue]];
NSString *strIntervalType = [parts objectAtIndex:1];

// string to date
NSString *myDateString = btnStartDate.titleLabel.text;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd MM yyyy"];
NSDate *datStartDate = [[NSDate alloc] init];
datStartDate = [dateFormatter dateFromString:myDateString];

NSString *strDesc = txtDescription.text;

FMDatabase* db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
if (![db open]) {
NSLog(@"Could not open db.");

if (![db tableExists:@"mytable"]) {
[db executeUpdate:@"CREATE TABLE 'mytable' ('pid' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'desc' VARCHAR,'sdate' DATETIME,'interval' INTEGER,'itype' VARCHAR,'price' DOUBLE);", nil];

[db beginTransaction];

[db executeUpdate:@"INSERT INTO mytable (desc,sdate,interval,itype,price) VALUES (?,?,?,?,?);",
strDesc, datStartDate, numInterval, strIntervalType, strAmount, nil];

//NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);

[db commit];
[db close];

by JM

Similar Posts:

Post a Comment

You must be logged in to post a comment.