javaee spring jdbc 查询方法
package com.test.dao.impl;
import com.test.dao.IUsersDao;
import com.test.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* @description:
* @projectName:testspring2
* @see:com.test.dao.impl
* @author:123
* @createTime:2023/8/28 21:56
*/
@Component
public class UsersDao implements IUsersDao {
//注入jdbcTemplate对象
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void add(Users user) {
String sql = "insert into users values(null,?,?)";
jdbcTemplate.update(sql, user.getName(), user.getPassword());
}
//查询 返回单个对象
public int selectUsersCount() {
String sql = "select count(*) from users";
int num = jdbcTemplate.queryForObject(sql, Integer.class);
return num;
}
//查询 返回集合
public List<Users> selectUsers() {
String sql = "select * from users";
List<Users> usersList= jdbcTemplate.query(sql, new RowMapper<Users>() {
//遍历结果集 将结果集中的每条数据 组装成Users对象
@Override
public Users mapRow(ResultSet resultSet, int i) throws SQLException {
return rowMapHander(resultSet);
}
});
return usersList;
}
public Users rowMapHander(ResultSet resultSet) throws SQLException {
Users user=new Users();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
return user;
}
}