0. Project의 타겟에 있는 Linked Frameworks and Libraries에 libsqlite3.dylib을 추가하자.

  또, 프로젝트 폴더에 .db 파일을 넣어주자.


1. NXViewController.h 파일에 다음을 추가하자.


#import <sqlite3.h>

@interface NXViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *table_view;

@property NSMutableArray * shopping_list;


2. db에 쿼리할 준비를 하자. NXViewController.m에 다음 코드를 추가하자.


NSString *dbFile = [[NSBundle mainBundle] pathForResource:@"shoppingList" ofType:".db"];


sqlite3 * db;

sqlite_open([dbFile cStringUsingEncoding:NSUTF8StringEncoding, &db);


sqlite_stmt * statement;

NSString * query = @"select * from shoppingTable";

sqlite_prepare(db, [query cStringUsingEncoding:NSUTF8StringEncoding], query.length, &statement, nil);


self.shopping_list = [[NSMutableArray alloc] init];


3. db에 쿼리를 날리고 배열에 정리하자.


while (sqlite3_step(statement) == SQLITE_ROW)

{

char * pItem = sqlite_column_text(statement, 0);

double aPrice = sqlite_column_double(statement, 1);

int aCount = sqlite_column_integer(statement, 2);


NSString * sItem = [NSString stringWithCString:pItem encoding:NSUTF8StringEncoding];

NSNumber * nPrice = [NSNumber numberWithDouble:aPrice];

NSNumber * nCount = [NSNumber numberWithInt:aCount];


NSArray * record = [NSArray arrayWithObjects:sItem, nPrice, nCount, nil];

[self.shopping_list addObject:record];

}


4. db에 쿼리가 끝났으면 db를 정리해주자.


sqlite3_finalize(statement);

sqlite3_close(db);


self.table_view.dataSource = self;




참고자료




Posted by 하남각목