要想管理连接池,首先得导入数据库相关包,这里就不多说了。
我们这里采取配置文件的方式写入配置
user=root
password=123
jdbcUrl=jdbc:mysql://localhost:3306/bjpowernode
driverClass=com.mysql.jdbc.Driver
这里有一个坑,那就是注意不要写username,因为 username代表的是当前用户的名称,而不是你数据库连接的用户名
下面是配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${dirverClass}"></property>
</bean>
</beans>
需要注意的是,要想用配置文件的方式进行配置的话,得引用外部配置文件,依赖context名称空间:
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"
然后就可以进行测试了
@Test
public void connectionTest() throws SQLException {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
DataSource dataSource = (DataSource) context.getBean("dataSource");
System.out.println(dataSource.getConnection());
}