对于电影做操作,在点击收藏时, 判断其是否被收藏.
并且删除, 插入喜爱的电影.
新建一个DataBaseTool
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#import "MovieModel.h"
typedef NS_ENUM(NSUInteger, SelectInTable) {
inTable,
NotInTable,
SelectError,
};
@interface DataBaseTool : NSObject
{
sqlite3 *dbPoint;
}
+ (DataBaseTool *)shareDataBaseTool;
// 打开数据库
//- (void)openDB;
//- (void)createTable;
- (SelectInTable)isSaveWithMovie:(MovieModel *)movie;
- (void)insertDataWithMovie:(MovieModel *)movie;
- (void)deleteDataWithMovie:(MovieModel *)movie;
内部实现:
#import "DataBaseTool.h"
@implementation DataBaseTool
+ (DataBaseTool *)shareDataBaseTool{
static DataBaseTool *dataTool;
static dispatch_once_t oneToKen;
dispatch_once(&oneToKen, ^{
dataTool = [[DataBaseTool alloc] init];
[dataTool openDB];
[dataTool createTable];
});
return dataTool;
}
- (void)openDB{
NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sandBoxPath = sandBox[0];
NSString *document = [sandBoxPath stringByAppendingPathComponent:@"Favorite.sqlite"];
int result = sqlite3_open([document UTF8String], &dbPoint);
if (result == SQLITE_OK) {
NSLog(@"数据库打开成功!");
}else{
NSLog(@"数据库关闭成功!");
}
}
- (void)createTable{
NSString *sqlStr = @"create table if not exists movie (number integer primary key autoincrement, movieID text, movieName text, pic_url text)";
int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
if (result == SQLITE_OK) {
NSLog(@"电影表创建成功!");
}else{
NSLog(@"电影表创建失败!%d",result);
}
}
- (SelectInTable)isSaveWithMovie:(MovieModel *)movie{
NSString *sqlStr =[NSString stringWithFormat:@"select * from movie where movieID = ‘%@‘",movie.movieID];
sqlite3_stmt *stmt = nil;
int result = sqlite3_prepare_v2(dbPoint, [sqlStr UTF8String], -1, &stmt, nil);
if (result == SQLITE_OK) {
NSLog(@"查询成功!");
if (sqlite3_step(stmt) == SQLITE_ROW) {
return inTable;
}else{
return NotInTable;
}
}else{
NSLog(@"查询失败!");
}
return SelectError;
}
- (void)insertDataWithMovie:(MovieModel *)movie{
NSString *sqlStr = [NSString stringWithFormat:@"insert into movie (movieID, movieName, pic_url)values (‘%@‘,‘%@‘,‘%@‘)",movie.movieID, movie.movieName, movie.pic_url];
int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
if (result == SQLITE_OK) {
NSLog(@"加入成功");
}else{
NSLog(@"加入失败!");
}
}
- (void)deleteDataWithMovie:(MovieModel *)movie{
NSString *sqlStr = [NSString stringWithFormat:@"delete from movie where movieID = ‘%@‘",movie.movieID];
int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
if (result == SQLITE_OK) {
NSLog(@"删除成功!");
}else{
NSLog(@"删除失败!");
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-29 19:10:51