とあるプログラマの備忘録

都内某所に住むプログラマが自分用に備忘録を残すという趣旨のブログです。はてなダイアリーから移動しました!

Cocos2dx sqlite3のバインド変数を使ってみる

クエリを書く際に

SELECT *  FROM `table` WHERE `id` =  256 AND `name` = "テキスト";

こんな感じになる場合プレースホルダに値をバインドしたくなるのが世の常です。

実際に書いてみる

    sqlite3 *db;
    sqlite3_stmt *stmt;
    const char *pzTest;

    //クエリ
    const char *sql = "SELECT *  FROM `table` WHERE `id` =  ? AND `name` = ?";
    sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, &pzTest);
    
    //バインド
    const char *name = "テキスト";
    sqlite3_bind_int(stmt, 1, 256);
    sqlite3_bind_text(stmt, 2, name, strlen(name), SQLITE_TRANSIENT);

こんな感じプレースホルダは番号を指定する事も出来る

    sqlite3 *db;
    sqlite3_stmt *stmt;
    const char *pzTest;

    //クエリ
    const char *sql = "SELECT *  FROM `table` WHERE `id` =  ?123 AND `name` = ?456";
    sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, &pzTest);
    
    //バインド
    const char *name = "テキスト";
    sqlite3_bind_int(stmt, 123, 256);
    sqlite3_bind_text(stmt, 456, name, strlen(name), SQLITE_TRANSIENT);

プレースホルダに文字列を使いたい場合は特定の記号から始める事で可能になる
使える記号は「: @ $」が使える。
只しその場合は sqlite3_bind_parameter_indexで第2引数変換する必要がある

    sqlite3 *db;
    sqlite3_stmt *stmt;
    const char *pzTest;

    //クエリ
    const char *sql = "SELECT *  FROM `table` WHERE `id` =  :id AND `name` = :name";
    sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, &pzTest);
    
    //バインド
    const char *name = "テキスト";
    sqlite3_bind_int(stmt, sqlite3_bind_parameter_index( stmt, ":id"), 256);
    sqlite3_bind_text(stmt, sqlite3_bind_parameter_index( stmt, ":name" ), name, strlen(name), SQLITE_TRANSIENT);

使い方はこんな感じ。

int sqlite3_bind_blob(sqlite3_stmt, int, const void, int n, void()(void)); int sqlite3_bind_double(sqlite3_stmt, int, double); int sqlite3_bind_int(sqlite3_stmt, int, int); int sqlite3_bind_int64(sqlite3_stmt, int, sqlite3_int64); int sqlite3_bind_null(sqlite3_stmt, int); int sqlite3_bind_text(sqlite3_stmt, int, const char, int n, void()(void)); int sqlite3_bind_text16(sqlite3_stmt, int, const void, int, void()(void)); int sqlite3_bind_value(sqlite3_stmt, int, const sqlite3_value); int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);

以下参考にさせていただきましたm()m

準備ステートメントへの値のバインド | Second Flush
[SQLite3] プレースホルダの位置に値を設定(バインド) | idocsq.net