1、Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
2、步骤:
1.导入jar包
2.创建JdbcTemplate对象,依赖于数据源DataSource
JdbcTemplate template = new JdbcTemplate ( ds) ;
3.调用JdbcTemplate的方法来完成CRUD的操作
(1)update():执行DML语句。增、删、改语句
(2)queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value,将这条记录封装为一个map集合
*注意:这个方法查询的结果集长度只能是1
(3)queryForList():查询结果将结果集封装为list集合
*注意:将每一条记录封装为一个Map集合,再将Map集合装载到List 集合中
(4)query():查询结果,将结果封装为JavaBean对象
* query的参数: RowMapper
*一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
* new BeanPropertyRowMapper < 类型> ( 类型. class )
(5)queryForObject :查询结果,将结果封装为对象
*一般用于聚合函数的查询
3、案例:
package dataSource. jdbcTemplate ;
import dataSource. domain. tUser ;
import org. junit. Test ;
import org. springframework. jdbc. core. BeanPropertyRowMapper ;
import org. springframework. jdbc. core. JdbcTemplate ;
import utils. Druid_JDBCUtil ;
import java. util. List ;
import java. util. Map ;
public class jdbcTemplate02 {
JdbcTemplate template = new JdbcTemplate ( Druid_JDBCUtil . getDataSource ( ) ) ;
@Test
public void test1 ( ) {
String sql = "update t_user set loginName = 'Marie' where id = 2" ;
int count = template. update ( sql) ;
System . out. println ( count) ;
}
@Test
public void test2 ( ) {
String sql = "insert into t_user(id,loginName,loginPwd,realName) values(?,?,?,?)" ;
int count = template. update ( sql, 3 , "lisi" , "123" , "李四" ) ;
System . out. println ( count) ;
}
@Test
public void test3 ( ) {
String sql = "delete from t_user where id = ?" ;
int count = template. update ( sql, 3 ) ;
System . out. println ( count) ;
}
@Test
public void test4 ( ) {
String sql = "select * from t_user where id = ?" ;
Map < String , Object > stringObjectMap = template. queryForMap ( sql, 1 ) ;
System . out. println ( stringObjectMap) ;
}
@Test
public void test5 ( ) {
String sql = "select * from t_user" ;
List < Map < String , Object > > maps = template. queryForList ( sql) ;
for ( Map < String , Object > m: maps) {
System . out. println ( m) ;
}
}
@Test
public void test6 ( ) {
String sql = "select * from t_user" ;
List < tUser> tUserList = template. query ( sql, new BeanPropertyRowMapper < tUser> ( tUser. class ) ) ;
for ( tUser t: tUserList) {
System . out. println ( t) ;
}
}
@Test
public void test7 ( ) {
String sql = "select count(id) from t_user" ;
Long count = template. queryForObject ( sql, long . class ) ;
System . out. println ( count) ;
}
}