今天学习了JDBCTemplate工具类的用法,JDBCTemplate是Spring框架针对JDBC的简单封装,下列代码就是一些JDBCTemplate的简单应用:
public class TemplateTest01 {
private static JdbcTemplate template =new JdbcTemplate(JDBCUtils.getDataSource());
// 4. 查询id为1的记录,将其封装为Map集合
@Test
public void methodMap(){
String sql="select * from emp where id=1001";
Map<String, Object> map = template.queryForMap(sql);
System.out.println(map);
}
5. 查询所有记录,将其封装为List
@Test
public void methodList(){
String sql="select * from emp";
List<Map<String, Object>> list = template.queryForList(sql);
System.out.println(list);
}
6. 查询所有记录,将其封装为Emp对象的List集合
@Test
public void methodEL(){
String sql="select * from emp";
List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
for (Emp emp : list) {
System.out.println(emp);
}
}
7. 查询总记录数*/
@Test
public void methodCount(){
String sql="select count(id) from emp";
Integer num = template.queryForObject(sql, Integer.class);
System.out.println(num);
}
} |
|