jdbctemplate.query的使用
时间: 2024-03-10 07:40:30 浏览: 254
jdbcTemplate的使用
JdbcTemplate是Spring框架中用于简化JDBC操作的一个工具类,其中query()方法是其中常用的方法之一。该方法可以执行SQL查询语句,并将结果映射为Java对象。
以下是JdbcTemplate中query()方法的使用示例:
1.查询并返回List类型的结果
```java
List<Account> accountList = jdbcTemplate.query("SELECT * FROM account", new RowMapper<Account>() {
@Override
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setId(resultSet.getInt("id"));
account.setUsername(resultSet.getString("username"));
account.setPassword(resultSet.getString("password"));
account.setBalance(resultSet.getDouble("balance"));
return account;
}
});
```
2.查询并返回单个对象
```java
Account account = jdbcTemplate.queryForObject("SELECT * FROM account WHERE id = ?", new Object[]{id}, new RowMapper<Account>() {
@Override
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setId(resultSet.getInt("id"));
account.setUsername(resultSet.getString("username"));
account.setPassword(resultSet.getString("password"));
account.setBalance(resultSet.getDouble("balance"));
return account;
}
});
```
3.查询并返回单个值
```java
int count = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM account", Integer.class);
```
阅读全文