错误的循环迭代iOS中的嵌套数据库查询.虽然循环未运行适当的次数



如果保留注释的部分,代码运行正常。虽然循环应运行两次,并且确实会导致线程表中只有两个行。while循环仅运行一次是错误的输出

sql = "select thread_id,timestamp from threads";
    if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
        while(sqlite3_step(selectstmt) == SQLITE_ROW) {
            NSString* abc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
            NSString* def = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
            NSLog(@"%@",abc);
            NSLog(@"%@",def);
            NSString* threadid = abc;
            NSString *sql2 = [NSString stringWithFormat:@"select * from my where t_id="%@"",threadid];
**Commented code begin**               
            /* sqlite3_finalize(selectstmt);
            sqlite3_open([path UTF8String], &database);
                if(sqlite3_prepare_v2(database, [sql2 UTF8String], -1, &selectstmt2, NULL) == SQLITE_OK) {
                int a = sqlite3_data_count(selectstmt2);
                NSLog(@"%d",a);
                    if (a==1) {
                    sql2 = [NSString stringWithFormat:@"select timestamp from my where t_id="%@"",threadid];
                        if(sqlite3_prepare_v2(database, [sql2 UTF8String], -1, &selectstmt2, NULL) == SQLITE_OK) {
                            while(sqlite3_step(selectstmt) == SQLITE_ROW) {
                            NSString* abc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt2, 0)];
                            NSLog(@"%@",abc);
                            }
                        }  
                    } 
                    if(a==0) {
                    char* error;
                    sql2 = [NSString stringWithFormat:@"insert into my(t_id,time) values("%@","%@")",threadid,@"0"];
                    int i = sqlite3_exec(database, [sql2 UTF8String], NULL, NULL, &error) ;
                    NSLog(@"inserted");
                    sqlite3_finalize(selectstmt);
                    }
              }*/
**Commented code end**
**program end**

您正在最终确定准备的语句,在您正在处理的同一循环中。毫不奇怪,下次尝试使用该语句时,它会失败。请注意,您对声明的每个呼叫(完成)完成后,将返回一个错误代码,您可以在继续使用其他逻辑之前检查该代码。

最新更新