선언부
#import <sqlite3.h>
@property (strong, nonatomic) NSString *dbPath;
구현부
[Sample1]
@Synthesize dbPath;
-(void)copyDatabaseIfNeeded{
//프로세스에 NSFileManager객체를 반환.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *eorror;
dbPath = [self getDBPath];
//dbPath가 경로에 있는지 확인하여 success값을 전달.
BOOL success = [fileManager fileExistsAtPath:dbPath];
//조건이 거짓일 경우! 새로운 DB 생성
if(!success){
NSString *defaultDBPath = [[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"DB.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:error];
if(!success)
NSAssert1(0, @"Failed to writable database file with message '%@'.", [error localizeDeion];
}
}
-(NSString *) getDBPath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"DB.sqlite"];
}
[Sample2]
#define DATABASE_NAME @"konglish"
#define DATABASE_EXT @"sqlite"
#defind DATAVATE_VERSION @"20120914_1"
//초기화
- (id) init
{
self = [super init];
if(self)
{
NSString *DBName = [NSString stringWithFormat:@"%@%@.%@", DATABASE_NAME,DATAVATE_VERSION,DATABASE_EXT ];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *defaultDBPath = [documentsDir stringByAppendingPathComponent:DBName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:defaultDBPath];
if(!success)
{
NSString *bundleDBName = [NSString stringWithFormat:@%@.%@, DATABASE_NAME, DATABASE_EXT];
NSString *defaultDBPath = [[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:bundleDBName];
NSError *eorror;
[fileManager copyItemAtPath:defaultDBPath toPath:defaultDBPath error:error];
}
dbPath = [documentsDirectory stringByAppendingPathComponent:DBName];
}
}
//데이터베이스 Select
- (NSMutableArray *) getSelect{
NSMutableArray *resultArray = [NSMutableArray alloc] init];
//데이터베이스를 연결
sqlite3 *database;
if(sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
sqlite3_close(database);
NSLOG(@"Error");
}
sqlite3_stm *selectStatement;
NSString *str = [NSString stringWithFormat:@"*"];
const char *selectSql = [str UTF8String];
if(sqlite3_prepare_v2(database, selectSql, -1, &selectStatement, NULL) == SQLITE_OK){
//while문을 돌면서 각 레코드의 데이터를 받아 출력
while(sqlite3_step(selectStatement)==SQLITE_ROW)
{
int test = sqlite3_column_int(selectStatement, 2);
NSString *eng_ = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 7)];
NSDictionary *resultDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d", test], @"test",
eng_, @"eng_", nil];
[resultArray addObject:resultDic];
}
}
//statement colse
sqlite3_finalize(selectStatement);
//DB colse
sqlite3_close(database);
return resultArray;
}
Frameworks추가
libsqlite3.0.dylib