JDBC Template

时间:2024-01-10 18:15:08

JDBC Template

1. Spring JDBC

  • Spring框架对JDBC的简单封装,提供了一个JDBCTemplate对象用来简化JDBC的开发
  • 步骤:
    1. 导入jar包
    2. 创建JDBCTemplate对象,参数要传递DataSource
      • template = new jdbcTemplate(dataSource)
    3. 调用jdbcTemplate对象的方法完成crud操作
      • update():执行增删改的DML语句
      • queryForMap():将查询结果封装为map集合
      • queryForList():将查询结果封装为List集合
      • query():查询结果,将结果封装为JavaBean对象
      • queryObject():查询结果,将结果封装为对象
public class jdbcTemplateTest {

    private JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());

    @Test// 添加一条记录
public void test1() {
//JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());
String sql = "insert into student values(null, ?, ?, ?, ?, ?)";
int update = template.update(sql, "紫霞仙子", 24, 100, "女", 90);
System.out.println(update);
} @Test // 删除一条记录
public void test2() {
String sql = "delete from student where id = ?";
int count = template.update(sql, 7);
System.out.println(count);
} @Test// 查询ID = 1的记录,封装为map集合
//要注意的是查询的结果集长度只能是1,将列名作为key,值作为value封装为map集合
public void test3() {
String sql = "select * from student where id = ?";
Map<String, Object> map = template.queryForMap(sql, 1);
System.out.println(map);
}
// 输出{id=1, name=唐三藏, age=25, english=60, sex=女, math=90} @Test// 将结果封装为List集合,里面装的是map集合
public void test4() {
String sql = "select * from student";
List<Map<String, Object>> maps = template.queryForList(sql);
for (Map<String, Object> map : maps) {
System.out.println(map);
}
} @Test// 将结果封装为javabean的List集合 BeanPropertyRowMapper完成查询结果自动封装为javabean对象
public void test5() {
String sql = "select * from student";
List<Student> list = template.query(sql, new BeanPropertyRowMapper<Student>(Student.class)); for (Student student : list) {
System.out.println(student);
}
} @Test // 总记录数// queryForObject一般用来查询聚合函数
public void test6() {
String sql = "select count(id) from student";
Long count = template.queryForObject(sql, Long.class);
System.out.println(count);
}
}