配置连接字符串
起因
昨天使用几种常用连接池,今天配置一下在项目中是如何使用的,明天则学习一下JDBCTemplate使用.数据库则改为PostgreSQL在项目中,会见连接数据库信息,写properties文件中,以键值对的存放.
mysql.properties文件内容:driver = com.mysql.jdbc.Driver
url = jdbc:mysql:///UserInfo
user = root
password = 123
在xml配置如何解析properties文件
<!-- 由PropertyPlaceholderConfigurer解析properties文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 指定properties文件所在路径 -->
<property name="locations" value="classpath:mysql.properties">
</property>
</bean>
<!-- c3p0 链接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 以${指定properties文件中key} -->
<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));");
}
}
效果:
秋风
2017-08-24