数据库中最后插入的行ID已成功插入,但获得的ID是0?
这是最后一行插入方法,返回我最后一个ID。数据库中最后插入的行ID已成功插入,但获得的ID是0?
代码:
-(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];
}
这是我想要得到的最后插入的行ID的方法,该方法
-(NSMutableArray *)loadImages1:(int)note_ID{ NSMutableArray *dataArray =[[NSMutableArray alloc] init];
NSString * sqlStr = [NSString stringWithFormat:@"SELECT * FROM image1 WHERE notes_id = %d",note_ID];
sqlite3_stmt *ReturnStatement = (sqlite3_stmt *) [self getStatement: sqlStr];
while(sqlite3_step(ReturnStatement) == SQLITE_ROW){
@try{
image1DC *imageData = [[image1DC alloc] init];
imageData.image1ID = [[NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement, 0)] intValue];
imageData.image1Name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement, 1)];
[dataArray addObject:imageData];
} @catch (NSException *ept) {
NSLog(@"Exception in %s, Reason: %@", __PRETTY_FUNCTION__, [ept reason]);
}
}
return dataArray;
}
回答:
LastId
函数就是ste ps通过表中的所有行,没有任何特定的顺序;它会返回一些随机ID。
要获取插入到同一数据库连接中的最后一个ID,请调用sqlite3_last_insert_rowid()函数。
要获得最大值的ID,请执行SELECT MAX(ID) FROM ...
。
回答:
这样做有一个
- 使用的SQLite的
- 的sqlite3_last_insert_rowid()方法使用MAX的两种方式(
your_auto_Incremental_primary_key_variable
)
我通常做的是俱乐部的sqlite3_last_insert_rowid()调用用插入语句获取最后插入的行ID
- (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;
}
以上是 数据库中最后插入的行ID已成功插入,但获得的ID是0? 的全部内容, 来源链接: utcz.com/qa/265415.html