数据库中最后插入的行ID是否已成功插入,但要获取该ID为0?

时间:2015-06-02 07:25:18

标签: ios objective-c iphone sqlite xcode6

这是最后一行插入方法,它返回最后一个id。

代码:

Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(10),
        new EventHandler<ActionEvent>() {
            public void handle(ActionEvent ae) {
                 // do stuff
            }
        }
));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();

这是我插入最后一个返回id的方法

-(int)LastId {
    int noteID;

    NSString * sqlStr;

    sqlStr = [NSString stringWithFormat:@"select * from notes"];

    sqlite3_stmt *ReturnStatement = (sqlite3_stmt *) [self getStatement: sqlStr];

    while(sqlite3_step(ReturnStatement) == SQLITE_ROW){

        @try{
            noteID=[[NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement, 0)] intValue];
        } @catch (NSException *ept) {
            NSLog(@"Exception in Method: '%@', Reason: %@", @"loadData", [ept reason]);
        }
    }

    return noteID;
}

这是我想要获取最后插入的行ID的方法

-(void)AddNoteImages1:(NSString *)imageName1 andID:(int)notesID{
    notesID = [self  LastId];

    NSString *query = [NSString stringWithFormat:@"insert into image1(image1Name,notes_id) values('%@','%d')",imageName1,notesID];

    [self InsUpdateDelData:query];
}

2 个答案:

答案 0 :(得分:2)

LastId函数只是遍历表中的所有行,没有任何特定的顺序;它将返回一些随机ID。

要在同一个数据库连接中插入最后一个ID,请调用sqlite3_last_insert_rowid()函数。

要获取具有最大值的ID,请执行SELECT MAX(ID) FROM ...

答案 1 :(得分:0)

有两种方法可以做到这一点

  1. 使用sqlite的sqlite3_last_insert_rowid()方法
  2. 使用MAX(your_auto_Incremental_primary_key_variable
  3. 我通常做的是使用insert语句调用sqlite3_last_insert_rowid()调用以获取最后插入的rowID

    - (BOOL)insertItem{
    
    const char *query = "your insert statement";
    sqlite3_stmt *sqlstatement = nil;
    
    if (sqlite3_prepare_v2(dbreference, query, -1, &sqlstatement, NULL)==SQLITE_OK) {
    
        //Your insert code here
    
        float rowID = sqlite3_last_insert_rowid(dbreference);
        NSLog(@"Last inserted row id = %.0f",rowID);
    
        sqlite3_close(dbreference);
    }
    
    return YES;
    }
    

    其中dbreference是sqlite3

    类型的变量

    如果上述解决方案不适合您的情况,那么您可以使用Max(ID)方法,该方法将接受存储主键的列名称,即自动增量

    - (int)getLastItemID{
    
    const char *query = "select MAX(userid) from SampleTable";
    sqlite3_stmt *sqlstatement = nil;
    if (sqlite3_prepare_v2(dbreference, query, -1, &sqlstatement, NULL)==SQLITE_OK) {
    
        while (sqlite3_step(sqlstatement)==SQLITE_ROW) {
    
            int lastInsertedPrimaryKey = sqlite3_column_int(sqlstatement, 0);
            return lastInsertedPrimaryKey;
        }
    
         sqlite3_close(dbreference);
    
    }
    
    return 0;
    }
    
相关问题