概述
是Spring框架的一个对象,对原始的Jdbc API进了封装,提供了很多的操作模板类。
开发步骤
导入spring-jdbc和spring-tx坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
直接使用
@Test
public void testJdbcTemplate() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("root");
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
jdbcTemplate.update("insert into accout values(?,?)","tom",5000);
}
通过Spring产生JdbcTemplate对象
配置数据源,由Spring创建
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///test"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
使用
@Test
public void testSpringJdbcTemplate(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean(JdbcTemplate.class);
jdbcTemplate.update("insert into accout values(?,?)","lucy",5000);
}
JdbcTemplate的常用操作
修改
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test02 {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testUpdate(){
jdbcTemplate.update("update accout set money=? where name=?",1000,"tom");
}
}
删除
@Test
public void testDelete(){
jdbcTemplate.update("delete from accout where name=?","tom");
}
查询全部
@Test
public void testQueryAll(){
List<Accout> accouts = jdbcTemplate.query("select * from accout", new BeanPropertyRowMapper<Accout>(Accout.class));
for (Accout accout : accouts) {
System.out.println(accout.getName());
}
}
查询单个数据
@Test
public void testQueryOne(){
Accout accout = jdbcTemplate.queryForObject("select * from accout where name=?", new BeanPropertyRowMapper<Accout>(Accout.class), "tom");
System.out.println(accout.toString());
}
@Test
public void testQueryCout(){
Long aLong = jdbcTemplate.queryForObject("select count(*) from accout", Long.class);
System.out.println(aLong);
}