【问题标题】:Sqlite3 table primary key gets replacedSqlite3 表主键被替换
【发布时间】:2012-10-18 11:31:33
【问题描述】:

我有一个 SQLite 数据库,其中我有一个名为 tblUser 的表,其中我有变量说 Id、name、image、gender。

在我的应用程序中,我提供了添加、删除更新用户条目的功能(通用功能)。假设我在有 2 个用户的页面上默认有 2 条记录,并且两者都被删除。现在插入的第 3 条记录将提供主键为 3。

现在,如果我编辑该特定记录,则不会使用新数据更新它,而是在我调用以下函数时将其主键替换为 1:

+ (void) getInitialDataToDisplay:(NSString *)dbPath
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //sqlite3_open([dbPath UTF8String], &database);
    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
    {
        const char *sql = "select UserId,UserAge,UserName,UserGender,UserImage from [tblUser]";
        sqlite3_stmt *selectstmt;
        if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
        {
            while(sqlite3_step(selectstmt) == SQLITE_ROW)
            {
                NSInteger primaryKey = sqlite3_column_int(selectstmt,0);
                UserDetail *DataObj = [[UserDetail alloc] initWithPrimaryKey:primaryKey];

                DataObj.UserAge = sqlite3_column_int(selectstmt,1);
                DataObj.UserName =    [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
                DataObj.UserGender =   [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
                DataObj.UserImage =   [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
                DataObj.isDirty = NO;
                [appDelegate.DataArray addObject:DataObj];
            }
        }
        else
        {
            NSAssert1(0,@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
        }
    }
    else
        sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}

请注意,当我在单击需要填写所有详细信息的页面的保存按钮后返回显示用户列表的页面时,我正在调用此函数。任何提示都会很有帮助。谢谢。

【问题讨论】:

  • SQLite 不会更改您的主键,因此其他地方肯定有错误。我建议向我们展示用于编辑记录的 SQL。
  • 另外,对于 CL,您如何确定插入记录的 UserId?如果您依赖 SQLite 为您执行此操作,请确保您使用 INTEGER PRIMARY KEY AUTOINCREMENT 而不仅仅是 INTEGER PRIMARY KEY。您可能想向我们展示您用于插入新记录的 SQL。你说它被插入为3,当你编辑时它变成了1,但我们都怀疑问题可能出在插入而不是编辑。

标签: objective-c ios sqlite


【解决方案1】:

假设UserIdINTEGER PRIMARY KEY: SQLite 将创建比先前最大值大一个的新 ID, 但是如果表是空的,它会(re)start at 1

【讨论】:

  • 但它允许我在删除所有记录后创建,只有在我编辑记录时才会出现问题..!!另请注意,主键是一个以 1 开头的整数。
  • 如果您的代码使用INTEGER PRIMARY KEY AUTOINCREMENT,SQLite 将不会在 1 处重新启动,即使表已被擦除。如果您重新创建表,它将重新启动。但如果您只是删除行并重新开始插入,则不会。
猜你喜欢
  • 1970-01-01
  • 2018-03-11
  • 2011-10-17
  • 2016-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
相关资源
最近更新 更多