概念
这是Spring对JDBC的简单封装,提供了一个JDBCTemplate对象简化JDBC的开发
步骤
(1)导入jar包
*commons-logging-1.2.jar
*spring-beans-5.1.10.RELEASE.jar
*spring-core-5.1.10.RELEASE.jar
*spring-jdbc-5.1.10.RELEASE.jar
*spring-tx-5.1.10.RELEASE.jar
(2)创建JdbcTemplate对象
JdbcTemplate template = new JdbcTemplate(ds);//ds为数据源DateSource
(3)调用相应方法进行sql的操作
相关方法
- update():执行DML语句,执行增删改语句:
@Test
public void test1(){
//2. 定义sql
String sql = "update emp set salary = 10000 where id = 1001";
//3. 执行sql
int count = template.update(sql);
System.out.println(count);
}
@Test
public void test2(){
String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
int count = template.update(sql, 1015, "郭靖", 10);
System.out.println(count);
}
- queryForMap():查询结果将结果集封装为Map集合,将列名做为key,将值作为value,将这条记录封装为一个Map集合 (注意:这个方法查询结果的结果集长度只能为1)
@Test
public void test4(){
String sql = "select * from emp where id = ? or id = ?";
Map<String, Object> map = template.queryForMap(sql, 1001,1002);
System.out.println(map);
//{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}
}
- queryForList():查询结果将结果集封装为List对象
*注意:将每一条记录封装为一个Map集合,再将Map集合封装为一个List集合
@Test
public void test5(){
String sql = "select * from emp";
List<Map<String, Object>> list = template.queryForList(sql);
for (Map<String, Object> stringObjectMap : list) {
System.out.println(stringObjectMap);
}
}
- query():查询结果,将结果封装为JavaBean对象
*query的参数:RowMapper
*一般使用BeanPropertyRowMapper实现类,可以完成数据到JavaBean的自动封装
*new BeanPropertyMapper<类型>(类型.Class)
@Test
public void test6_2(){
String sql = "select * from emp";
List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
for (Emp emp : list) {
System.out.println(emp);
}
}
- queryForObject():查询结果,将结果封装为对象
*一般用于聚合函数的查询
@Test
public void test7(){
String sql = "select count(id) from emp";
Long total = template.queryForObject(sql, Long.class);
System.out.println(total);
}