无法更新或在表中插入行

时间:2014-07-26 21:14:03

标签: ios database sqlite

我想在我的iPhone应用中更新一行。下面是代码。它在我的日志中显示执行查询并且行已更新,但是当我超出该表时,它似乎是空的。即使我尝试输入具有新id的行,它也总是更新一行,在这种情况下它应该插入而不是更新。

 //create local database
NSString *docsDir = NULL;
 NSArray *dirPaths = NULL;
 sqlite3 *localDB = NULL;

 // Get the documents directory
 dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 docsDir = [dirPaths objectAtIndex:0];

 // Build the path to the database file
 NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"localscentsy1.db"]];
 NSLog(@"%@",databasePath);

 const char *dbpath = [databasePath UTF8String];
 sqlite3_stmt *statement = NULL;

 if (sqlite3_open(dbpath, &localDB) == SQLITE_OK)
 {

     NSString *updateSQL = [NSString stringWithFormat:@"UPDATE Ratings set rating = '%d' WHERE perfume_id = ?",
                            (int)rating];


     const char *update_stmt = [updateSQL UTF8String];
     if(sqlite3_prepare_v2(localDB, update_stmt, -1, &statement, NULL ) ==SQLITE_OK){

         sqlite3_bind_int(statement, 1, tappedItem.perfumeId);
     }

     char* errmsg;
     sqlite3_exec(localDB, "COMMIT", NULL, NULL, &errmsg);

     if(SQLITE_DONE != sqlite3_step(statement)){
         NSLog(@"Error while updating. %s", sqlite3_errmsg(localDB));

         NSLog(@"query failed: %s", sqlite3_errmsg(localDB));
         NSLog(@"%@",@"update unsuccessfull");
         NSLog(@"New data, Insert Please");

         sqlite3_stmt *statement2 = NULL;
         NSString *insertSQL = [NSString stringWithFormat:
                                @"INSERT INTO Ratings (perfume_id,rating) VALUES (\"%d\",\"%d\")",
                                tappedItem.perfumeId,
                                (int)rating];

         const char *insert_stmt = [insertSQL UTF8String];
         sqlite3_prepare_v2(localDB, insert_stmt, -1, &statement2, NULL);
         if (sqlite3_step(statement2) == SQLITE_DONE)
         {
             NSLog(@"New data, Inserted");
         }
         sqlite3_finalize(statement2);

     }
     else{
         NSLog(@"%@",@"update successfull");
         sqlite3_finalize(statement);
     }


    sqlite3_close(localDB);
 }

任何帮助将不胜感激。我是ios开发的新手,这段代码占用了我很多时间。这是我的日志,总是说"更新成功"

    CyberGenies/Library/Application Support/iPhone Simulator/7.0/Applications/24D2FEE2-              DBE6-441A-AC79-1F2D57F96C88/Documents/localscentsy1.db
    2014-07-27 01:03:26.612 Scentsy Squirrel[19008:a0b] update successfull

1 个答案:

答案 0 :(得分:0)

你看过db真的有结构吗?有时,当您开始在空数据库中进行查询时(我的意思是甚至不是表),查询本身会构建您在查询中提供它的结构。您可以通过在模拟器上进行编译来检查并在Mac查找程序中查找数据库。