IOC整合JDBC模板&連線池(17)
阿新 • • 發佈:2018-12-10
整合Spring自帶連線池
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring4_day03"/>
<property name="username" value="root"/>
<property name="password" value="abc"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
整合DBCP連線池
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring4_day03"/>
<property name="username" value="root"/>
<property name="password" value="abc"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<property name="dataSource" ref="dataSource" />
</bean>
整合C3P0連線池
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///spring4_day03"/>
<property name="username" value="root"/>
<property name="password" value="abc"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
配置屬性檔案
把屬性檔案提取出來有助於結構層次的清晰。需要修改值的時候,只需要維護屬性檔案就可以了。
#屬性檔案
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/jdbc-study
jdbc.name=root
jdbc.password=root
<!-- 引入屬性檔案-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 使用屬性檔案的值 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.name}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
C3P0的測試
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
String sql = "insert into students(id, name, clazz) values(?, ?, ?)";
jt.update(sql, "160341237", "詹金浩", "1234");
}
}