All of the interesting technological, artistic or just plain fun subjects I'd investigate if I had an infinite number of lifetimes. In other words, a dumping ground...

Friday, 13 August 2010

Using sqlite3 - C programming example

void select_stack_shuffle(const char * database, const char * blk_lbl, int blk_lbl_len)
{
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;

    rc = sqlite3_open(database, &db);
    if ( rc ) {
        fprintf(stderr, "sqlite4: Can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return;
    }
    const unsigned int sql_str_len = 1024;
    char sql_str[sql_str_len];
    strcpy(sql_str, "SELECT ctr_key, deadline FROM stack_shuffle WHERE block = ?1 AND still_there = 1;");
    sqlite3_busy_timeout(db, 500);
    sqlite3_stmt * pStmt;
    const char * pzTail;
    rc = sqlite3_prepare(db, sql_str, -1, &pStmt, &pzTail);
    // rc = sqlite3_prepare_v2(db, sql_str, -1, &pStmt, &pzTail);
    if ( rc != SQLITE_OK ) {
        fprintf(stderr, "sqlite4: Can't prepare statement: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return;
    }
    rc = sqlite3_bind_text(pStmt, 1, blk_lbl, blk_lbl_len, SQLITE_STATIC);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "sqlite4: bind failed: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return;
    }
    do {
        rc = sqlite3_step(pStmt);
        if (rc == SQLITE_ROW) {
            int cols = sqlite3_column_count(pStmt);
            int col_1_type = sqlite3_column_type(pStmt, 0);
            int col_2_type = sqlite3_column_type(pStmt, 1);
            printf("sqlite4: %s: %d columns, type col 1 %d, type col 2 %d\n", __FUNCTION__, cols, col_1_type, col_2_type);
            int ctr_key = sqlite3_column_int(pStmt, 0);
            const unsigned char * deadline = sqlite3_column_text(pStmt, 1);
            printf("sqlite4: %s: ctr_key %d, deadline %s\n", __FUNCTION__, ctr_key, deadline);

        } else {
            if (rc != SQLITE_DONE) {
                printf("sqlite4: %s: received a %d, %s\n", __FUNCTION__, rc, sqlite3_errmsg(db));
            }
        }
    } while (rc == SQLITE_ROW);

}

No comments:

tim's shared items

Add to Google Reader or Homepage