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);