xcode에서 FMDB사용하기

#import “/usr/include/sqlite3.h” #import “FMDatabase.h” #import “FMDatabaseAdditions.h” @interface AddressExSecondViewController : UIViewController { sqlite3 *testDB; NSString *databasePath; } @end [/crayon] 실제로는 아래와 같이 사용하면 된다.. [crayon] // — SQL READY —————————————————————————————————- NSString *docsDir; NSArray *dirPaths; // Applications Directoryを取得する // (Ex) /Users/jojh/Library/Application Support/iPhone Simulator/5.1/Applications/ dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); docsDir = [dirPaths objectAtIndex:0]; NSLog(@”docsDir=%@”, docsDir); // Build the path to the database file databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @”testdb.sqlite”]]; NSLog(@”databasePath=%@”, databasePath); // ファイルが存在するかチェックする。 NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL success = [fileManager fileExistsAtPath:databasePath]; if (!success){ // TODO Do something } // — ↓↓ FMDB を使ってDBに接続する方法 ↓↓ ——————————————————————————- FMDatabase* connection = [FMDatabase databaseWithPath: databasePath]; if (![connection open]) { NSLog(@”Could not open db.”); return; } [connection setShouldCacheStatements:YES]; [connection beginTransaction]; [connection executeUpdate:@”insert into test values (?, ?)”, [NSNumber numberWithInt:2], @”b”]; [connection commit]; FMResultSet *rs = [connection executeQuery:@”select * from test”]; while ([rs next]) { NSLog(@”IndexID:[%d], Name:[%@]”, [rs intForColumn:@”indexId”], [rs stringForColumn:@”name”]); } [rs close]; [connection close]; /* // — ↓↓ sqlite3を使ってDBに接続する方法 ↓↓ ——————————————————————————- // — SQL INSERT ————————————————————————————————— sqlite3_stmt *statement; const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &testDB) == SQLITE_OK) { NSString *insertSQL = [NSString stringWithFormat: @”INSERT INTO test VALUES (1, ‘a’)”]; const char *insertStatement = [insertSQL UTF8String]; sqlite3_prepare_v2(testDB, insertStatement, -1, &statement, NULL); if (sqlite3_step(statement) == SQLITE_DONE) { NSLog(@”INSERTに成功しました。”); } else { NSLog(@”INSERT FAILED…”); } sqlite3_finalize(statement); sqlite3_close(testDB); } // — SQL SELECT ————————————————————————————————— if (sqlite3_open(dbpath, &testDB) == SQLITE_OK) { NSString *querySQL = [NSString stringWithFormat: @”SELECT indexId, name FROM test”]; const char *queryStatement = [querySQL UTF8String]; if (sqlite3_prepare_v2(testDB, queryStatement, -1, &statement, NULL) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { int indexId = sqlite3_column_int(statement, 0); NSString *name = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)]; NSLog(@”IndexID:[%d], Name:[%@]”, indexId, name); } sqlite3_finalize(statement); } sqlite3_close(testDB); } */ [/crayon] 그런데 아래와 같은 에러가 발생했다.. _main함수가 중복된다는 에러인데, 해결방법은 fmdb.m 파일을 지우면된다. ]]>

Related Posts