I’m new to using sqlite and the iPhone and I’m having some trouble adding a record to my database. I’ve used what I can online to try and solve this problem but I’m stuck in a rut.
I’m using this piece of code to attempt to add a record into the database in sqlite:
-(void)insertData{
sqlite3 *database;
sqlite3_stmt *statement;
NSString *databasePath = [[NSBundle mainBundle] pathForResource:@"ProductDatabase" ofType:@"sql"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
//nutrional values
float caloriesFloat = [caloriesTextField.text floatValue];
float saturatesFloat = [saturatesTextField.text floatValue];
float fatFloat = [fatTextField.text floatValue];
float fibreFloat = [fibreTextField.text floatValue];
float sugarFloat = [sugarTextField.text floatValue];
float saltFloat = [saltTextField.text floatValue];
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO products (name,category,calories, saturates,fat,fibre,sugar,salt) VALUES ('%@',' %@','%.02f','%.02f','%.02f','%.02f','%.02f','%.02f',);",nameTextField.text, categoryLabel.text, caloriesFloat, saturatesFloat, fatFloat, fibreFloat, sugarFloat, saltFloat];
const char *insert_stmt = [insertSQL UTF8String];
if(sqlite3_prepare_v2(database, insert_stmt, -1, &statement, nil)== SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [nameTextField.text UTF8String], -1, NULL);
sqlite3_bind_text(statement, 2, [categoryLabel.text UTF8String], -1, NULL);
sqlite3_bind_text(statement, 3, [[NSString stringWithFormat:@"%f", caloriesFloat] UTF8String], -1, NULL);
sqlite3_bind_text(statement, 3, [[NSString stringWithFormat:@"%f", saturatesFloat] UTF8String], -1, NULL);
sqlite3_bind_text(statement, 3, [[NSString stringWithFormat:@"%f", fatFloat] UTF8String], -1, NULL);
sqlite3_bind_text(statement, 3, [[NSString stringWithFormat:@"%f", fibreFloat] UTF8String], -1, NULL);
sqlite3_bind_text(statement, 3, [[NSString stringWithFormat:@"%f", sugarFloat] UTF8String], -1, NULL);
sqlite3_bind_text(statement, 3, [[NSString stringWithFormat:@"%f", saltFloat] UTF8String], -1, NULL);
}
if(sqlite3_step(statement)==SQLITE_DONE)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Added" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Not Added" message:@"An error has occured" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
alert=nil;
}
// Release the compiled statement from memory
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
The alert view “Product not added” always appears, can anyone explain why my record isn’t being added?
Thanks,
Jack
Its because you are directly writing data to
databasein resources folder.it is not writable first you need to copy thedatabaseindocument directory.Add the code written below after the above line
and remove the bind statements from the code and change it to