起因
昨天使用几种常用连接池,今天配置一下在项目中是如何使用的,明天则学习一下JDBCTemplate使用.数据库则改为
PostgreSQL
在项目中,会见连接数据库信息,写properties文件中,以键值对的存放.
mysql.properties文件内容:
driver = com.mysql.jdbc.Driver
url = jdbc:mysql:///UserInfo
user = root
password = 123
在xml配置如何解析properties文件
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:mysql.properties">
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
测试配置是否可用
package qiufeng.spring.jdbctemplate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:mysql.xml")
public class JdbcTemplateTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void springTestC3p0() {
jdbcTemplate.execute("create table User4(id int primary key,name varchar(16));");
}
}
效果: