一、使用JdbcTemplate
JdbcTemplate是spring框架中提供的一个对象, 对原始繁琐的Jdbc API对象的简单封装。
spring框架为我们提供了很多的操作模板类。例如:
- 操作关系型数据的JdbcTemplate和HibernateTemplate
- 操作nosql数据库的RedisTemplate
- 操作消息队列的ImsTemplate
…
1、导入spring-jdbc和spring-tx坐标
2、创建数据库表和实体
3、创建JdbcTemplate对象
4、执行数据库操作
public void test1() throws PropertyVetoException {// 创建数据源对象ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.set JdbcUr1("jdbc:mysql://localhost:3306/test");dataSource.setUser("root");dataSource.setPassword("root");JdbcTemplate jdbcTemplate = new JdbcTemplate();//设置数据源对象知道数据库在哪jdbcTemplate.setDataSource(dataSource);//执行操作int row = jdbcTemplate.update("insert into account values(?, ?)", "tom", 5000) ;System.out.println(row);}
二、spring产生JdbcTemplate对象
我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到JdbcTemplate模版对象中,配置如下:
<!--数据源DataSource--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value ="com.mysql.jdlbe.Driver"></property><property name="jdbcUrl" value ="jdlba:mysql:///test"></property><property name ="user" value="root"></property><property name ="password" value="root"></property></bean><!--JdbcTemplate--><bean id ="jdbaTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean>
