JDBCTemplate初学简介
JDBCTemplate
-
JdbcTemplate是Spring的一部分,是对数据库的操作在jdbc的封装,处理了资源的建立和释放(不需要我们管理连接了),我们只需要提供SQL语句(不需要我们设置参数了)和提取结果(查询时候可以直接返回对应的实体类),使JDBC更加易于使用。
JdbcTemplate使用spring的注入功能,把DataSource注册到JdbcTemplate之中。 - DataSource是JDBC2.0 提供了javax.sql.DataSource接口,它负责建立与数据库的连接,当在应用程序中访问数据库时不必编写连接数据库的代码,直接引用DataSource获取数据库的连接对象即可。用于获取操作数据Connection对象。
-
除了JDBC外都有DataSource对象。
DataSource可以看作数据源,它封装了数据库参数,连接数据库,程序中操作DataSource对象即可对数据库进行增删改查操作。
不同方式中使用的DataSource对象不同。列举如下:
1,DBCP框架
dbcp框架中的DataSource类是:org.apache.commons.dbcp.BasicDataSource
这是commons-dbcp.jar包中的类。
2,C3P0框架
c3p0框架的DataSource类是:com.mchange.v2.c3p0.ComboPooledDataSource
这是c3p0.jar包中的类。
3,MyBatis框架
MyBatis框架的DataSource类是:org.apache.ibatis.datasource.pooled.PooledDataSource
这是mybatis.jar包中的类。
- jdbcTemplate的方法使用
update:执行增删改操作
1 JdbcTemplate jdbcTemplate = new JdbcTemplate(unitl.getDataSource()); 2 3 String sql6 = "update emp set ename='sb' where ename=?"; 4 int update = jdbcTemplate.update(sql6,"庞统"); 5 System.out.println(update);
queryForMap查询结果集长度只能为1的map集合,值为value,列名为key
String sql = "select * from emp where ename =?"; Map<String, Object> stringObjectMap = jdbcTemplate.queryForMap(sql,"关羽"); System.out.println(stringObjectMap);
queryForList将查询到的结果集放到list集合中,一条数据是一条map集合
String sql2 = "select * from emp"; List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql2); System.out.println(maps);
queryForObject查询结果封装为对象,一般是用于聚集函数
String sql7 = "select count(*) from emp"; Integer integer = jdbcTemplate.queryForObject(sql7, Integer.class); System.out.println(integer);
query查询结果封装为javabean对象。query的参数:rowMapper。一般使用BeanPropertyRowMapper完成自动封装
List<Emp> emp = jdbcTemplate.query(sql2, new BeanPropertyRowMapper<Emp>(Emp.class)); System.out.println(emp);
数据库连接池的使用:c3p0,需要相应的jar包和c3p0-config.xml文件
DataSource comboPooledDataSource = new ComboPooledDataSource(); for (int i = 0; i < 10; i++) { Connection connection = comboPooledDataSource.getConnection(); System.out.println(connection); }
数据库连接池的使用:druid,需要相应的jar包和druid.properties文件
Properties properties = new Properties(); try { resource= unitl.class.getClassLoader().getResource("druid.properties").toURI(); }catch (URISyntaxException e){ e.printStackTrace(); } try { properties.load(new FileInputStream(new File(resource))); }catch (IOException e){ e.printStackTrace(); } try { dataSource = DruidDataSourceFactory.createDataSource(properties); }catch (Exception e){ e.printStackTrace(); } Connection con = dataSource.getConnection();