sos の 作業メモ

プログラミングや英会話学習、マイルや旅行、日常生活など。最近はWebFormなASP.NETのお守りがお仕事です。

日々の生活にhappyをプラスする|ハピタス Gポイント

SQLite3を使うよ その3 読み込み

その2の続き

書き込めるようになったので、今度は読み込みです。

SQLを元にPreparedStatementを作るところまでは一緒で、あとは sqlite3_stepの戻り値がSQLITE_ROWの間、データをfetch(一レコードずつ読み込み)します

読み込み

データタイプに応じた読み取りメソッドを用意。注意する点は、カラムのインデックスが0から始まることです。 書き込むときは1でしたが、読み込む時は0です。 これに気づかずに半日悩みました。

+ (int)columnInt:(sqlite3_stmt*)pstmt index:(int)index
{
    return sqlite3_column_int(pstmt, index);
}

+ (int64_t)columnInt64:(sqlite3_stmt*)pstmt index:(int)index
{
    return sqlite3_column_int64(pstmt, index);
}

+ (double)columnDouble:(sqlite3_stmt*)pstmt index:(int)index
{
    return sqlite3_column_double(pstmt, index);
}

+ (NSString*)columnText:(sqlite3_stmt*)pstmt index:(int)index
{
    const unsigned char* text = sqlite3_column_text(pstmt, index);
    if (text) {
        return [NSString stringWithUTF8String:(const char*)text];
    } else {
        return nil;
    }
}

+ (BOOL)columnBlob:(sqlite3_stmt*)pstmt index:(int)index withBuffer:(NSMutableData*)buffer
{
    int length = sqlite3_column_bytes(pstmt, index);
    if(length > 0){
        [buffer appendBytes:sqlite3_column_blob(pstmt, index) length:length];
        return YES;
    } else {
        return NO;
    }
}

読み込み実例

かなりはしょりますが、実際の読み込みはこんな感じ。くれぐれも、インデックスが0から始まるのを忘れないでください。

sqlite3_stmt* pstmt = [TFDBTool prepareStatement:_database query:"select id from mytable"];
if(pstmt){
    while (sqlite3_step(pstmt) == SQLITE_ROW) {
        int val = [TFDBTool columnInt:0];
        NSLog(@"%d",val);
    }
    [TFDBTool finalizeStatement:pstmt];
}

これでSQLiteもばっちりです。