我有一个sqlite数据库,我想在其中插入行。我使用此代码插入行并进行查询。

   -(void)InsertRecords{

    querySQL1 = @"select category from notes where id=5";
    const char * query_stmt = [querySQL1 UTF8String];

    sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);

    NSString *insertSQL = [NSString stringWithFormat:
                           @"INSERT INTO notes (id, title, content,dataAdd,category) VALUES (\"%@\", \"%@\", \"%@\" ,\"%@\",\"%@\")",
                           @"5",
                           @"georgiana",
                           @"20",
                           @"12.09.2019",
                           @"public"];

    const char *insert_stmt = [insertSQL UTF8String];
    sqlite3_stmt *updateStmt = nil;

    sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
    if(sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL) == SQLITE_OK){

    if (sqlite3_step(statement) == SQLITE_DONE)
    {
        NSLog(@"data inserted");

    }
    else{
        NSLog(@"Error while creating update statement. '%s'", sqlite3_errmsg(contactDB));

    }
    }


    else
        NSLog(@"Error while creating update statement. '%s'", sqlite3_errmsg(contactDB));




    querySQL1 = @"select id from notes where category LIKE 'public'";
    query_stmt = [querySQL1 UTF8String];

    sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);

   NSString *idNr=@"";
    while (sqlite3_step(statement) == SQLITE_ROW)
    {
        idNr =[NSString stringWithUTF8String:
               (const char *) sqlite3_column_text(statement, 0)];

    }

    NSLog(@"%@",idNr);

    sqlite3_finalize(statement);
    sqlite3_close(contactDB);
}


一切正常,但是当我再次打开应用程序时,idNr没有任何值。

任何有用的帮助将不胜感激。

最佳答案

NSString分配是错误的语句,这里不需要alloc NSString对象。

方法stringWithUTF8String:是类方法。这将为NSString进行分配。

替换您的代码,如下所示:

NSString *idNr = @"";
while (sqlite3_step(statement) == SQLITE_ROW) {
    idNr = [NSString stringWithUTF8String:
                 (const char *) sqlite3_column_text(statement, 0)];

}

10-04 15:51