UI 19 資料庫的練習,ui19資料庫練習
對於電影做操作,在點擊收藏時, 判斷其是否被收藏.
並且刪除, 插入喜愛的電影.
建立一個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(@"刪除失敗!"); } }
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。