データベースの書き方(FMDB)
データベース接続
- (FMDatabase *)getConnection { if( self.db_path == nil ) { self.db_path = [このクラス getDbFilePath]; //このクラスのクラスメソッド } return [FMDatabase databaseWithPath:self.db_path]; }
+ (NSString*)getDbFilePath { NSArray* paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES ); NSString* dir = [paths objectAtIndex:0]; return [dir stringByAppendingPathComponent:@"todo.db"]; //データベースのファイル名 }
そしてDBクラスのインスタンス生成時に自動でDBに接続できるようにイニシャライザで設定しておく
- (id)init { self = [super init]; if( self ) { FMDatabase* db = [self getConnection]; [db open]; [db executeUpdate:_createDB]; [db close]; } return self; }
_createDBの部分は定数で定義してある
static NSString *const createDB = @"@"CREATE TABLE IF NOT EXISTS t_todo (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, contents TEXT, limit_date DATE);"
DBから値の取り出し
①select文で値を取り出すとき ②NSMutableArray型の変数生成 ③while文でモデルオブジェクトクラスのプロパティに値を格納 ④NSMutableArrayに格納 ⑤db close 忘れない
FMDatabase* db = [self getConnection]; [db open]; FMResultSet* results = [db executeQuery:@"SELECT id, title, date FROM t_todo" ]; NSMutableArray* todos = [[[NSMutableArray alloc] initWithCapacity:0] autorelease]; while( [results next] ) { ToDo* todo = [[Book alloc] init]; todo.todoId = [results intForColumnIndex:0]; todo.title = [results stringForColumnIndex:1]; todo.contents = [results stringForColumnIndex:2]; todo.date = [results dateForColumnIndex:3]; [todos addObject:todo]; } [db close];