2011年2月19日土曜日

Sqlite3でDBを結合する方法

openできるDBはひとつだけなので
結合するDBはATTACHで指定する。

まず以下の関数を作成する。

- (void)Attach:(sqlite3 *)hDB DB:(NSString *)dbName
{
NSString *attachSQL = [NSString stringWithFormat: @"ATTACH '%@' as %@",[[NSBundle mainBundle]
                                    pathForResource:dbName ofType:@"db"],dbName];
const char *sql_stmt = [sql UTF8String];
char *errMsg;
if (sqlite3_exec(hDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
 NSLog(@"AttachSQL failed : %s",errMsg);
}

使い方はこんな感じ(エラー処理は略)
sqlite3 *contactDB;
const char *dbpath = [[NSString stringWithFormat: @"ATTACH '%@' as %@",[[NSBundle mainBundle]
                                    pathForResource:@"mainDB" ofType:@"db"],dbName] cString];
sqlite3_open(dbpath, &contactDB);
[self Attach:contactDB DB:@"secondDB"];
querySQL = [NSString stringWithFormat: @"SELECT a.id, b.Comment
                   FROM mainDB a, secondDB b
                   WHERE a.id=b.song AND a.key=\"ABC\""];
const char *query_stmt = [querySQL UTF8String];
sqlite3_stmt    *statement;
sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement,NULL);
sqlite3_step(statement);
・・・

0 件のコメント:

コメントを投稿