Using Query Parameters

In Hazelcast clients, you can use query parameters to build safer, faster SQL queries.

What is a Query Parameter

A query parameter is a piece of information that you supply to a query before you run it. Parameters can be used by themselves or as part of a larger expression to form a criterion in the query.

int ageToCompare = 30;
sql.execute("SELECT name FROM employees WHERE employees.age > ?", ageToCompare);

Instead of putting data straight into an SQL statement, you use the ? placeholder in your client code to indicate that you will replace that placeholder with a parameter.

Benefits of Query Parameters

Query parameters have the following benefits:

  • Faster execution of similar queries. If you submit more than one query where only a value changes, the SQL service uses the cached query plan from the first query rather than optimizing each query again.

  • Protection against SQL injection. If you use query parameters, you don’t need to escape special characters in user-provided strings.

  • Inserting values into OBJECT fields from the Java client. OBJECT fields are used for arrays, nested objects, or enums (anything for which we don’t have a more specific type). You can use query parameters to query these values.

Example

Consider a map called employees whose values are Employee objects with the following fields.

Name

Type

name

String

age

Int

You can use a parameterized query to find employees who are older than a given integer:

int ageToCompare = 30;
sql.execute("SELECT name FROM employees WHERE employees.age > ?", ageToCompare);
To use parameterized queries to compare one object to another, you must add the object’s class to the member. Doing so allows the member to convert the parameter to an instance of the object.