sqlite3在iPhone应用程序中插入或替换语法问题

时间:2011-11-26 03:38:40

标签: iphone ios xcode sqlite

我在sqlite3插入或替换语法时遇到错误;

我的应用程序崩溃,无法进入prepare_v2语句条件。 我的代码如下:

NSString *plquery = @"INSERT OR REPLACE INTO LIST (COUNT, NAME, DATE, IDNUM) VALUES (?, ?, ?, ?) WHERE IDNUM = '";
        NSString *update = [plquery stringByAppendingFormat:@"%i%@",[accessID integerValue],@"'"];
        NSLog(@"%@",update);

        sqlite3_stmt *stmt;
        if (sqlite3_prepare_v2(database, [update UTF8String], -1, &stmt, nil)== SQLITE_OK)
        {
            NSLog(@"reaches here");
            sqlite3_bind_int(stmt, 1, i);
         }
         if (sqlite3_step(stmt) != SQLITE_DONE)
        NSAssert1(0, @"Error updating table: %s", errorMsg); 

1 个答案:

答案 0 :(得分:6)

您无法插入并在同一声明中的位置。您有3个选择:

  1. 如果您希望更改已存在的行,请将“插入或替换”更改为“更新”。
  2. 删除where语句以添加新行。
  3. 如果您不确定该行是否存在但是先执行'select'语句,则使用上述2个选项执行if else。
  4. 选项1看起来像:

     NSString * update = [NSString stringWithFormat:@"UPDATE LIST SET COUNT = ?, NAME = ?, DATE = ?, IDNUM = ? WHERE IDNUM = '%i'", [accesID integerValue]];
    

    选项2看起来像:

    NSString * update = [NSString stringWithFormat:@"INSERT OR REPLACE INTO LIST (COUNT, NAME, DATE, IDNUM) VALUES (?, ?, ?, ?)"];
    

    选项3看起来像:

    NSString * update = [NSString stringWithFormat:@"SELECT * FROM LIST WHERE IDNUM = '%i'", [accessID integerValue]];
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, [update UTF8String], -1, &stmt, nil);
    if (rc == SQLITE_OK) {
        if (sqlite3_step(stmt) == SQLITE_ROW) {
            update = [NSString stringWithFormat:@"UPDATE LIST SET COUNT = ?, NAME = ?, DATE = ?, IDNUM = ? WHERE IDNUM = '%i'", [accessID integerValue]];
        }
        else{
            update = [NSString stringWithFormat:@"INSERT OR REPLACE INTO LIST (COUNT, NAME, DATE, IDNUM) VALUES (?, ?, ?, ?)"];   
        }
    }