バインディング変数の使用

バインディング変数を宣言するには、PreparedStatementのインスタンスを作成する必要があります。PreparedStatementのインスタンスは、KVStore.prepare()メソッドを使用して作成できます。

ゼロ個以上の変数宣言を指定できます。変数の構文は次のとおりです。

DECLARE $varname vartype; 

DML文に外部変数が含まれる場合、BoundStatementのインスタンスを作成することでPreparedStatementを複数回実行できます。外部変数は、文を実行する前に特定の値にバインドする必要があります。同じPreparedStatementを、毎回異なるバインド値を使用して同時に複数回実行できるようにするには、外部変数のバインドをBoundStatementの1つ以上のインスタンスを使用して実行する必要があります。そのようなインスタンスは、createBoundStatement()メソッドを使用して作成されます。

このインスタンスはKVStore.execute()メソッドまたはKVStore.executeSync()メソッドを使用して複数回実行できます。

次に例を示します。

// store handle creation omitted.

...

// Compile the statement.
PreparedStatement pStmt = store.prepare(
   "DECLARE $minAge integer; $maxAge integer;  " +
   "SELECT id, firstName FROM Users WHERE
    age >= $minAge and age < $maxAge ");

// Iterate decades
for( int age = 0; age <= 100; age = age + 10 ) {

    int maxAge = age + ( age < 100 ? 10 : 1000 );
    System.out.println("Persons with ages between " + age +
    " and " + maxAge + ".");
    // Bind variables, reuse the same pStmt
    BoundStatement bStmt = pStmt.createBoundStatement();
    bStmt.setVariable("$minAge", age);
    bStmt.setVariable("$maxAge", maxAge);

    // Execute the statement
    StatementResult result = store.executeSync(bStmt);

    // Get the results in the current decade
    for( RecordValue record : result ) {

    System.out.println("id: " +
    record.get("id").asInteger().get() );
    System.out.println("firstName: " +
    record.get("firstName").asString().get());
    }
}