我有以下代码,我一直在获取数据库锁,因为没有调用sqlite3_finalize。但是,我不确定如何使用我的代码执行此操作。
-(BOOL) saveLogin:(NSString*)access_token expires_in:(NSString*)expires_in refresh_token:(NSString*)refresh_token token_type:(NSString*)token_type saved:(NSString*)saved;{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK){
NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO login (access_token,expires_in, refresh_token, token_type, saved) values (\"%@\",\"%@\", \"%@\", \"%@\", \"%@\")",access_token,expires_in, refresh_token, token_type, saved];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_close(database);
return YES;
}else {
NSLog(@"Error %s while preparing statement", sqlite3_errmsg(database));
sqlite3_close(database);
return NO;
}
}
sqlite3_close(database);
return NO;
}
答案 0 :(得分:0)
你的逻辑不必要地复杂。
您应该重新组织代码,以便所有清理工作都在一个地方完成:
BOOL result = NO;
if (sqlite3_open(dbpath, &database) == SQLITE_OK) {
if (sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL) == SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_DONE) {
result = YES;
} else {
NSLog(@"Error executing statement: %s", sqlite3_errmsg(database));
}
sqlite3_finalize(statement);
} else {
NSLog(@"Error preparing statement: %s", sqlite3_errmsg(database));
}
sqlite3_close(database);
} else {
// open failed
}
return result;
请注意,为每次访问重新打开数据库都是不必要的努力;你应该在应用程序启动时只打开一次。