spring xml使用bean管理数据库连接池
ioc2.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"></property>
<property name="password" value="***"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mqtt"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
</bean>
</beans>
Test.java
public static void main(String[] args) throws BeansException, SQLException {
String fileName = "ioc2.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(fileName);
DataSource datasource = (DataSource) context.getBean("datasource");
// System.out.println(datasource.getConnection());
Connection connection = datasource.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from user");
while (resultSet.next()) {
int userid = resultSet.getInt("userid");
System.out.println(userid);
}
}
使用加载配置文件方式管理数据库连接池
ioc2.xml
<context:property-placeholder location="classpath:jdbc.properties"/>
jdbc.properties
user=root
passwd=***
#jdbcUrl=jdbc:mysql:localhost:3306/mqtt
jdbcUrl=mysql://localhost:3306/mqtt
driverClass=com.mysql.jdbc.Driver
总结
spring通过ioc容器创建并管理数据库连接池,并且使用单例模式,保证了数据库的长时间连接