0
点赞
收藏
分享

微信扫一扫

Spring JDBC模板(C3P0)

早安地球 2022-04-16 阅读 117

1.先引入对应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);

    }
举报

相关推荐

0 条评论