1.先导入spring-jdbc和spring-tx坐标,引入对应jar包 此处为mysql---c3p0(maven POM.xml)
2.jdbc配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.username=root
jdbc.password=123456
2.Spring配置文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.1配置context命名空间-->
<!--2..加载jdbc,properties文件方式,外部引入 需要Conetxt命名空间 配置之后,下面的数据源对象就可以引入,解耦,-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--3. 配置c3p0数据源对象 内部方式引入配置-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 4. JDBC模板对象 注入数据源对象-->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
3.测试
//Spring 产生jdbc模板对象
@Test
public void test2() throws PropertyVetoException {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class);
int jierui = jdbcTemplate.update("insert into account values (?,?)", "配置文件", 90000);
System.out.println(jierui);
}
3.2简化注解注入方式测试(推荐)(先导入test和junit坐标)
//1.@RunWith是junit运行于spring环境
@RunWith(SpringJUnit4ClassRunner.class)
//2.引入配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class jdbcTemplateCRUDTest {
@Autowired//就不用里面去new 和getBean()
// Jdbc模板对象ID=JdbcTemplate
private JdbcTemplate jdbcTemplate;
// ============================================================================
@Test
public void testUpdate(){
int tom = jdbcTemplate.update("update account set money=? where name=?", 999, "tom");
System.out.println(tom);
}
@Test
public void testUpdate2(){
int tom2 = jdbcTemplate.update("delete from account where name=?","zhangsan");
System.out.println(tom2);
}
}