jeudi 9 avril 2015

Entering data into database iOS Objective-c

Trying to enter data from a form into a database, the code breaks when executing the sql statement.. not exactly sure why..


DBManager.m



-(BOOL)createDB{

NSString* docDir;
NSArray* dirPath;

dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

docDir = dirPath[0];

self.dbPath = [[NSString alloc]initWithString:[docDir stringByAppendingString:@"restaurant2.db" ]];

NSFileManager *fmgr = [NSFileManager defaultManager];
BOOL isSuccess = YES;
if (![fmgr fileExistsAtPath:self.dbPath]) {
const char* dbpath = [self.dbPath UTF8String];
if (sqlite3_open(dbpath, &database)==SQLITE_OK) {
char* errMsg;
const char* sql_stmt =
"create table if not exists restaurant(id integer primary key autoincrement, name text, address text, phone text,description text, tags text)";

if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)!=SQLITE_OK) {
isSuccess = NO;
NSLog(@"Failed to create database");

}
sqlite3_close(database);
return isSuccess;
}else{
isSuccess=NO;
NSLog(@"Failed to open/create database");
}
}


return isSuccess;


}

-(BOOL)saveData:(NSString*)name address:(NSString*)address phone:(NSString*)phone description:(NSString*)description tags:(NSString*)tags{

const char* dbpath = [self.dbPath UTF8String];

BOOL res = YES;
if(sqlite3_open(dbpath, &database)== SQLITE_OK){
NSString *insertSQL = [NSString stringWithFormat:@"insert into restaurant(name, address, phone, description, tags) values (\"%@\",\"%@\",\"%@\",\"%@\"),\"%@\")", name,address,phone,description, tags];

const char* insert_stmt = [insertSQL UTF8String];

sqlite3_prepare(database, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement)!= SQLITE_DONE){
NSLog(@"Failed to execute the query %@", insertSQL);
res = NO;

}
sqlite3_reset(statement);
}
else{
res = NO;
NSLog(@"Failed to open database");
}


return res;
}


addRestaurantController.m



- (IBAction)addRestaurant:(id)sender {

BOOL success = NO;

NSString* alertMSG = @"Insert Failed";
if (self.name.text.length > 0 && self.address.text.length > 0){
success = [[DBManager getSharedInstance] saveData:self.name.text address:self.address.text phone:self.phone.text description:self.descriptions.text tags:self.tags.text];
}

else{
alertMSG= @"Enter the name and address at least";
}
if(!success){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:alertMSG message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}


This is where I think its breaking located in DBManager.m



sqlite3_prepare(database, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement)!= SQLITE_DONE){
NSLog(@"Failed to execute the query %@", insertSQL);
res = NO;

}

Aucun commentaire:

Enregistrer un commentaire