Hint
This article is generated by AI translation.
Positional Arguments
When SQL uses ?, you can bind arguments to the corresponding zero-based index.
select * from users where id > ? and status = ?
Usage
Example 1: Arguments with an array
Object[] args = new Object[] { 2, "Dave"};
jdbcTemplate.queryForList("select * from users where id > ? and name = ?", args);
Example 2: Arguments with a List
List<?> args = Arrays.asList(2, "Dave");
jdbcTemplate.queryForList("select * from users where id > ? and name = ?", args);
Example 3: Omit the array when only one argument is used
jdbcTemplate.queryForList("select * from users where id > ?", 2);
Naming
Each ? positional argument implicitly has a name. The naming rule is arg<index>, for example: arg0, arg1.
Example 4: Use named positional arguments
Object[] args = new Object[] { 2, "Dave"};
jdbcTemplate.queryForList("select * from users where id > :arg0 and name = :arg1", args);
- For other named-argument syntaxes, see Named Arguments.
Argument Options
Use the SqlArg class to provide more control when setting arguments, such as specifying a TypeHandler, Java type, or JDBC type.
Example 1: Use SqlArg to specify TypeHandler
SqlArg[] args = new SqlArg[] {
SqlArg.valueOf(2L, new LongTypeHandler()), // LongTypeHandler sets a Long argument
SqlArg.valueOf("Dave", new StringTypeHandler())// StringTypeHandler sets a String argument
};
jdbcTemplate.queryForList("select * from users where id > ? and name = ?", args);
SqlArg provides multiple factory methods for creating different types of arguments:
| Method | Description |
|---|---|
SqlArg.valueOf(Object) | Create an IN argument |
SqlArg.valueOf(Object, Class<?>) | Create an IN argument with javaType |
SqlArg.valueOf(Object, TypeHandler<?>) | Create an IN argument with TypeHandler |
SqlArg.valueOf(Object, int) | Create an IN argument with jdbcType |
SqlArg.asOut(String, int) | Create an OUT argument (with jdbcType) |
SqlArg.asOut(String, int, TypeHandler<?>) | Create an OUT argument (with jdbcType + TypeHandler) |
SqlArg.asInOut(String, Object, int) | Create an INOUT argument (with jdbcType) |
SqlArg.asInOut(String, Object, int, TypeHandler<?>) | Create an INOUT argument (with jdbcType + TypeHandler) |
SqlArg objects can also be placed directly in a Map as named argument values. The framework automatically recognizes and uses their type information.
Example 2: Mixing SqlArg and plain values in Map
Map<String, Object> args = new HashMap<>();
args.put("id", SqlArg.valueOf(2L, new LongTypeHandler()));
args.put("name", "Dave");
jdbcTemplate.queryForList("select * from users where id > :id and name = :name", args);
For more argument options, see: