JdbcTemplate支持以下几种类型的参数绑定:
- 基本类型:
jdbcTemplate.update("UPDATE user SET name = ? WHERE id = ?", "John", 1);
- 日期类型:
Date date = new Date();
jdbcTemplate.update("UPDATE user SET birth_date = ? WHERE id = ?", date, 1);
- 字符串:
jdbcTemplate.update("UPDATE user SET name = ? WHERE id = ?", "John", 1);
- 数组:
String[] names = {"John", "Jack", "James"};
jdbcTemplate.update("INSERT INTO user (name) VALUES (?)", names);
- 集合:
List<String> names = Arrays.asList("John", "Jack", "James");
jdbcTemplate.update("INSERT INTO user (name) VALUES (?)", names);
- 自定义对象:
User user = new User(1, "John", 30);
jdbcTemplate.update("INSERT INTO user (id, name, age) VALUES (?, ?, ?)",
user.getId(), user.getName(), user.getAge());
- Null值:
jdbcTemplate.update("UPDATE user SET birth_date = ? WHERE id = ?", null, 1);
JdbcTemplate会根据传入参数的值自动选择使用PreparedStatement
还是Statement
来执行SQL,无需手动设置。所以,相比直接使用JDBC,JdbcTemplate的参数绑定更灵活简便。