数据库中为了open,createTable,放入初始化方法里
+ (DataBaseHandle *)shareDB{
static DataBaseHandle *db = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
db = [[DataBaseHandle alloc] init];
// 让他就执行一次,下次使用的时候还在
[db openDB];
[db createTable];
});
return db;
}
- (void)openDB{
NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES) lastObject];
NSString *dbPath = [sandBoxPath stringByAppendingPathComponent:@"Activity.sqlite"];
NSLog(@"%@", dbPath);
int result = sqlite3_open([dbPath UTF8String], &dbPoint);
if (result == SQLITE_OK) {
NSLog(@"open ok");
} else {
NSLog(@"wrong");
}
}
- (void)createTable{
// NSString *sqlStr = @"create table if not exists activity (activityId text, title text)";
NSString *sqlStr = @"create table if not exists activity (activityId text, title text, flag integer)";
int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
if (result == SQLITE_OK) {
NSLog(@"创建表成功");
} else {
NSLog(@"失败");
}
}
判断当前操作的数据有没有收藏(用枚举返回)
// 状态细分,写枚举
typedef NS_ENUM(NSUInteger, SelectType) {
InTable,
NotInTable,
selectError,
};
- (SelectType)actIsInTable:(Activity *)act{
NSString *sqlStr = [NSString stringWithFormat:@"select * from activity where activityId = '%@' and flag = '1'", act.activityId];
// 跟随指针
sqlite3_stmt *stmt = nil;
// 执行
int result = sqlite3_prepare_v2(dbPoint, [sqlStr UTF8String], -1, &stmt, nil);
if (result == SQLITE_OK) {
// 如果在这一行里查到了数据,就返回有值,没有查到,就返回没有
if (sqlite3_step(stmt) == SQLITE_ROW) {
sqlite3_finalize(stmt);
return InTable;
} else {
sqlite3_finalize(stmt);
return NotInTable;
}
} else {
sqlite3_finalize(stmt);
return selectError;
}
}
逻辑删除
- (void)insertAct:(Activity *)act{
NSString *sqlStr = [NSString stringWithFormat:@"insert into activity(title,activityId,flag) values ('%@','%@','1')", act.title, act.activityId];
int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
if (result == SQLITE_OK) {
NSLog(@"添加成功");
} else {
NSLog(@"失败");
}
}
- (void)updateAct:(Activity *)act{
NSString *sqlStr = [NSString stringWithFormat:@"update activity set flag = '0' where activityId= '%@'", act.activityId];
int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
if (result == SQLITE_OK) {
NSLog(@"成功");
} else {
NSLog(@"失败");
}
}
物理删除
- (void)deleteAct:(Activity *)act{
NSString *sqlStr = [NSString stringWithFormat:@"delete from activity where activityId = '%@'", act.activityId];
int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
if (result == SQLITE_OK) {
NSLog(@"删除成功");
} else {
NSLog(@"失败");
}
}