我是新來使用sqlite和iPhone,我有一些麻煩添加一條記錄到我的數據庫。我已經使用了我可以在線的方式嘗試解決這個問題,但我陷入了一種尷尬的境地。插入數據到iPhone上的sqlite數據庫 - 不工作
我使用這段代碼試圖將記錄添加到數據庫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);
}
}
警報視圖「不添加產品」總是出現,任何人都可以解釋爲什麼我的紀錄ISN」 t被添加?
感謝,
傑克
你可以使用'sqlite3_errmsg(數據庫)'來澄清問題是什麼? – FluffulousChimp 2012-03-14 17:29:37
Dupe of http://stackoverflow.com/questions/2785211/sqlite3-database-doesnt-actually-insert-data-iphone – MishieMoo 2012-03-14 17:39:32