jdbcTemplate 實現查詢返回list
阿新 • • 發佈:2019-01-08
package spring_jdbctemplate; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class JdbcTemplateDemo2 { @Test public void delete(){ DriverManagerDataSource dataSource=new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://xxxx:3306/test"); dataSource.setUsername("hpn"); dataSource.setPassword("hpn2017"); //常見JdbcTemplate物件,設定資料來源 JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource); //設定sql語句 String sql="select * from test2"; List<User> list=jdbcTemplate.query(sql, new MyRowMapper()); System.out.println(list); } } class MyRowMapper implements RowMapper<User>{ @Override public User mapRow(ResultSet rs, int num) throws SQLException { //從結果集裡把資料得到 String username=rs.getString("username"); String password=rs.getString("password"); //把資料封裝到物件裡 User user=new User(); user.setUsername(username); user.setPassword(password); return user; } }
返回結果:[User [username:yangyang,password:123], User [username:haha,password:456], User [username:hehe,password:567]]