-1

我无法在数据库中插入新行。我究竟做错了什么?

-(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);
}
4

1 回答 1

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')";

而且你的方法有很多错误,比如如果数据库没有打开,prepare语句总是会执行。无论是否执行准备语句,Finalize 语句都将始终有效。所以像这样重写它:

-(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));
    }
}
于 2012-11-10T12:41:17.657 回答