【问题标题】:'INSERT INTO' suddenly give back error 'PRIMARY KEY must be unique''INSERT INTO' 突然返回错误 'PRIMARY KEY 必须是唯一的'
【发布时间】:2023-04-01 03:41:01
【问题描述】:

我的 iOS 应用上有一个 sqlite 数据库。 我发现列的数字有误,然后我改成正确的数字,从那以后我得到一个错误“主键必须是唯一的”。 在错误之前一切顺利(除了 2 列错位的值)。

我的代码:

- (BOOL)createGroupMemberTable {
    char *error = NULL;
    const char *sqlStatment = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (ID INTEGER PRIMARY KEY AUTOINCREMENT, %@ INTEGER, %@ INTEGER, '%@' TEXT, '%@' TEXT, '%@' TEXT, '%@' TEXT, '%@' TEXT, '%@' TEXT, '%@' TEXT, '%@' TEXT);", kTableNameGroupMember, kMemberID, kGroupID, kName, kTime, kLatitude, kLongitude, kMobile, kVisible, kAddress, kPicture].UTF8String;
    int responseCode = sqlite3_exec(_database, sqlStatment, NULL, NULL, &error);
    
    if (responseCode != SQLITE_OK) {
        sqlite3_close(_database);
        printf("Table 'GroupMember' failed to create, responseCode: %i\n", responseCode);
        return NO;
    }
    else {
        return YES;
    }
}

- (BOOL)addGroupMember:(GroupMember*)aGroupMember {
    char *error = NULL;
    const char *sqlStatment = [NSString stringWithFormat:@"INSERT INTO %@ ('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@') VALUES (%i, %i, '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@');", kTableNameGroupMember, kMemberID, kGroupID, kName, kTime, kLatitude, kLongitude, kMobile, kVisible, kAddress, kPicture, aGroupMember.memberID, aGroupMember.groupID, aGroupMember.name, aGroupMember.time, aGroupMember.latitude, aGroupMember.longitude, aGroupMember.mobile, aGroupMember.visible, aGroupMember.address, aGroupMember.picture].UTF8String;
    int responseCode = sqlite3_exec(_database, sqlStatment, NULL, NULL, &error);
    
    if (responseCode != SQLITE_OK) {
        printf("\n\nFailed to insert into 'GroupMember' table, responseCode: %i\n", responseCode);
        printf("Error Message: %s\n\n", sqlite3_errmsg(_database));
        return NO;
    }
    else {
        return YES;
    }
}

这可能无关紧要,但这是我创建数据库的代码:

static SQLiteHandler *_database;

+ (SQLiteHandler*)database {
    if (_database == nil) {
        _database = [[SQLiteHandler alloc] init];
    }
    return _database;
}

- (NSString*)databasePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths objectAtIndex:0];
    return [docDirectory stringByAppendingPathComponent:@"social.sqlite3"];
}

- (id)init {
    if ((self = [super init])) {
        const char *fileName = [self databasePath].UTF8String;
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%s", fileName]]) {
            printf("SQLITE EXISTS\n");
        }
        else {
             printf("SQLITE NOT EXISTS\n");
            const char *finalPath = [self databasePath].UTF8String;
            printf("File 'social.sqlite3' created at path: %s\n", finalPath);
        }
           
        
        printf("fileName: %s\n", fileName);
        int responseCode = sqlite3_open(fileName, &_database);
        
        if (responseCode != SQLITE_OK) {
            printf("Failed to open database, responseCode: %i\n", responseCode);
        }
        
        [self createGroupTable];
        [self createGroupMemberTable];
    }
    return self;
}

错误日志:

无法插入“GroupMember”表,responseCode: 19 错误 消息:PRIMARY KEY 必须是唯一的

define SQLITE_CONSTRAINT 19 /* 由于违反约束而中止 */

有什么想法吗?

编辑:

答案正如我最终所想的那样,正如“Petesh”在这里评论的那样。 所有答案都是正确的,所以我会标记第一个。

【问题讨论】:

  • 大胆猜测,您已经在尝试使用更新后的代码添加的数据库中获得了具有组成员 ID 的数据。你是如何生成这个会员ID的?您是否有旧的成员 ID 现在阻止插入新 ID,因为您正试图回收新插入中的数字?当您遇到密钥冲突时,您应该转储表格的内容或冲突的 id,这在这种情况下会有所帮助
  • 好的,这就是我的想法,我现在替换了我的代码,它可以工作了。

标签: ios objective-c database sqlite


【解决方案1】:

您正在插入具有相同主键(成员 ID)的组成员。您应该尝试检查该成员 ID 是否存在于数据库中。

如果组成员已经存在,您也可以决定替换所有值,使用 INSERT OR REPLACE INTO:

[NSString stringWithFormat:@"INSERT OR REPLACE INTO %@ ('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@') VALUES (%i, %i, '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@');", kTableNameGroupMember, kMemberID, kGroupID, kName, kTime, kLatitude, kLongitude, kMobile, kVisible, kAddress, kPicture, aGroupMember.memberID, aGroupMember.groupID, aGroupMember.name, aGroupMember.time, aGroupMember.latitude, aGroupMember.longitude, aGroupMember.mobile, aGroupMember.visible, aGroupMember.address, aGroupMember.picture].UTF8String;

【讨论】:

    【解决方案2】:

    您正在尝试使用数据库中已存在的主键插入/更新记录。再次查看您尝试更改的记录的主键,看看您的数据库中是否存在具有相同主键(特定记录的唯一标识符)的记录。

    【讨论】:

      【解决方案3】:

      主键是数据库识别每一行的方式,因此您不能插入与已使用的主键相同的记录。

      看起来正在发生的事情是,当您在错误后重新启动时,您没有先删除应用程序,因此它使用了已经创建的数据库,而不是从头开始重新启动。然后,当您调用 addGroupMember 时,它重用了 kTableNameGroupMember 的值,我认为这是您的主键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-01
        • 1970-01-01
        • 2012-09-10
        • 1970-01-01
        • 1970-01-01
        • 2021-02-13
        • 1970-01-01
        相关资源
        最近更新 更多