SQLiteのメモ
SQLiteのDBファイルはアプリのドキュメントフォルダにある必要がありますが、今回はリソースフォルダに初期DBファイルを置き、ドキュメントフォルダに存在しない場合(初回起動)の場合にリソースフォルダよりコピーして使う方法をとります。
SQLiteやDBの知識があることを前提にして書いてるので、SQLに関することは別で調べてください。
DBファイルの作成と追加
OSX上でsqliteを使ってDBファイルを作成します。
例としてテーブルを1つだけ定義したファイルを作成します。
$ sqlite3 test.db sqlite> create table TABLEA ( ...> a integer, ...> b text ...> );
作成したDBファイルをプロジェクトの"Resources"へ追加します

SQLiteのファイルを管理するのに便利なツールを紹介します。Adobe Airの環境で動きます。
Lita - SQLite Administration Tool
SQLite用ライブラリの追加
SQLiteを使うためのライブラリ"libsqlite3.0.dylib"をプロジェクトの"Frameworks"へ追加します。
libsqlite3.0.dylib"は
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS(OSのバージョン).sdk/usr/lib/
にあります。リンクファイルではなく、実ファイルを選択してください。

DBファイルのコピーとファイル名取得。
ドキュメントフォルよりDBファイルのパスを含むファイル名を取得します。ドキュメントフォルダに存在しない場合(初回起動)の場合にリソースフォルダよりコピーしたあと、パスを含むファイル名を取得します。
BOOL success;
NSError *error;
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasepath = [documentsDirectory stringByAppendingPathComponent:@"test.db"];
NSString *dbpath = [[NSString alloc] initWithString:databasepath];
success = [fm fileExistsAtPath:dbpath];
if(!success){
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.db"];
success = [fm copyItemAtPath:defaultDBPath toPath:dbpath error:&error];
if(!success){
NSLog([error localizedDescription]);
}
}
// 処理後にどこかで [dbpath release] を実行すること!dbpathにDBファイルのファイル名が代入されます。
DBのオープン
DBのオープン〜SQL実行〜検索結果取得〜DBクローズ
test.dbにいくつかデータが入っていると仮定します。
// DBのオープン
if (sqlite3_open([dbpath UTF8String], &database) == SQLITE_OK) {
// SQL文の定義
char *sql = "select A,B from TABLEA";
// SQLを実行して結果を取得
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
// 取得件数分繰り返し
while(sqlite3_step(statement) == SQLITE_ROW) {
// 数値項目 A(0番目の項目) の取得
NSInteger a = sqlite3_column_int(statement, 0);
// 文字列項目 B(1番目の項目) の取得
NSString *b = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
// コンソールに結果を表示
NSLog(@"A:%d, B:%s", id, [name cStringUsingEncoding:NSUTF8StringEncoding]);
}
sqlite3_finalize(statement);
}
// DBのクローズ
sqlite3_close(database);
}
SQLiteのデータ型
TEXT 文字列
INTEGER 整数
REAL 小数
BLOB バイナリ

- 作者: Erica Sadun,株式会社クイープ
- 出版社/メーカー: ソフトバンククリエイティブ
- 発売日: 2009/02/12
- メディア: 大型本
- 購入: 20人 クリック: 474回
- この商品を含むブログ (60件) を見る