使用Spring配置數據源JdbcTemplate


 

c3p0作為演示

1.編寫資源文件(db.properties)

jdbc.user=root
jdbc.password=root
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring
jdbc.driverClass=com.mysql.jdbc.Driver

 

2.在SpringXML配置中獲取數據源資源文件

<context:property-placeholder location="classpath:db.properties"/>
 

3.配置c3p0的連接參數

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
    </bean>

 

4.配置spring的jdbcTemplale bean

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>    
 </bean>

 

到這里數據源已經配置好了,直接獲取bean就可以使用了。

案例:

修改前的數據:

修改后的數據:

操作代碼:

ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");
String sql = "update tb_student set name='lisi' where id=2 ";
jdbcTemplate.update(sql);

其他的操作和原生jdbc沒什么太大區別。

 

配置NamedParameterJdbcTemplate只需要通過構造注入dataSource就OK

<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
      <constructor-arg ref="dataSource"></constructor-arg>
</bean>

操作代碼:

NamedParameterJdbcTemplate jdbcTemplate = (NamedParameterJdbcTemplate)                 
        ac.getBean("namedParameterJdbcTemplate");
        String sql = "update tb_student set name=:name where id=:id ";
        Map<String, Object> map = new HashMap();
        map.put("name","lisi2");
        map.put("id",2);
        jdbcTemplate.update(sql, map);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM