Executing queries
The Java SDK provides methods for executing raw SurrealQL queries against SurrealDB. You can run single or multi-statement queries, bind parameters for safe variable injection, and call server-side functions.
API References
Running a query
The .query() method executes one or more SurrealQL statements and returns a Response. Use .take(int) to extract the result of a specific statement by its zero-based index, or .take(Class, int) to deserialize the result into a typed Java object.
Response response = db.query("SELECT * FROM users; SELECT * FROM posts;");
Value users = response.take(0);
List<Post> posts = response.take(Post.class, 1);
Using query parameters
The .queryBind() method accepts a Map<String, ?> of parameters that are safely injected into the query. Parameterized queries prevent SurrealQL injection and ensure values are properly escaped.
Map<String, Object> params = Map.of("min_age", 18);
Response response = db.queryBind(
"SELECT * FROM users WHERE age > $min_age",
params
);
List<User> users = response.take(User.class, 0);
Always prefer .queryBind() over string concatenation when incorporating user-provided values into queries.
Working with query responses
The Response object contains the results of all statements in the query. Use .take(int) to get a raw Value, or .take(Class, int) to deserialize into a POJO. The .size() method returns the number of statement results.
Response response = db.query(
"CREATE users SET name = 'Alice'; SELECT * FROM users;"
);
int statementCount = response.size();
Value created = response.take(0);
List<User> users = response.take(User.class, 1);
See Value types for details on working with the Value class and type conversions.
Running SurrealDB functions
The .run() method calls a server-side function defined with DEFINE FUNCTION. Pass the function name and any arguments.
Value result = db.run("fn::calculate_total", 100, 0.2);
Learn more