我无法在数据库中插入新行。我究竟做错了什么?
-(void)InsertRecords{
fileMgr = [NSFileManager defaultManager];
sqlite3_stmt *stmt;
sqlite3 *cruddb;
const char *sql = "Insert into AllDictionary(id, DeleteFlag, TitleBD, Description, PathToDB, ImageURL) VALUES('565','asasf2','asfas2ff','fggaga2hah','b2bb','aa2aa')";
NSString *cruddatabase = [self.GetDocumentDirectory stringByAppendingPathComponent:@"MainDb.sqlite"];
if(!(sqlite3_open([cruddatabase UTF8String], &cruddb)==SQLITE_OK))
{
NSLog(@"An error has occured: %s",sqlite3_errmsg(cruddb));
}
if (sqlite3_prepare(cruddb, sql, -1, &stmt, NULL)!=SQLITE_OK) {
NSLog(@"Problem with prepare statement: %s", sqlite3_errmsg(cruddb));
} else {
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
sqlite3_close(cruddb);
}
答案 0 :(得分:2)
您的Id类型为int。 所以问题在于查询,
const char *sql = "Insert into AllDictionary(id, DeleteFlag, TitleBD, Description, PathToDB, ImageURL) VALUES('565','asasf2','asfas2ff','fggaga2hah','b2bb','aa2aa')";
不要对整数值使用引号来表示字符串值。 将查询更改为:
const char *sql = "Insert into AllDictionary(id, DeleteFlag, TitleBD, Description, PathToDB, ImageURL) VALUES(565,'asasf2','asfas2ff','fggaga2hah','b2bb','aa2aa')";
您的方法中存在很多错误,例如,如果未打开db,则始终会执行prepare语句。 Finalize语句将始终使用或不执行prepare语句。 所以重新写一下:
-(void)InsertRecords
{
fileMgr = [NSFileManager defaultManager];
NSString *cruddatabase = [self.GetDocumentDirectory stringByAppendingPathComponent:@"MainDb.sqlite"];
sqlite3_stmt *stmt;
sqlite3 *cruddb;
const char *sql = "Insert into AllDictionary(id, DeleteFlag, TitleBD, Description, PathToDB, ImageURL) VALUES(565,'asasf2','asfas2ff','fggaga2hah','b2bb','aa2aa')";
if((sqlite3_open([cruddatabase UTF8String], &cruddb)==SQLITE_OK))
{
if (sqlite3_prepare(cruddb, sql, -1, &stmt, NULL) ==SQLITE_OK)
{
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
else
{
NSLog(@"Problem with prepare statement: %s", sqlite3_errmsg(cruddb));
}
sqlite3_close(cruddb);
}
else
{
NSLog(@"An error has occured: %s",sqlite3_errmsg(cruddb));
}
}