一般常用的连接池是DBCP和C3P0.
package cn.itcast.spring3.demo1; import java.sql.DriverManager; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.jta.SpringJtaSynchronizationAdapter; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class SpringTest1 { @Autowired @Qualifier("jdbcTemplate") private JdbcTemplate jdbcTemplate;//注入Jdbc模板 @Test public void demo2(){ jdbcTemplate.execute("create table user (id int primary key auto_increment,name varchar(20))"); } @Test public void demo1(){ // 创建连接池: DriverManagerDataSource dataSource = new DriverManagerDataSource();//Spring自带的连接池 // 设置参数: dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql:///spring3_day02"); dataSource.setUsername("root"); dataSource.setPassword(""); //使用JDBC的模板: //JdbcTemplate jdbcTemplate = new JdbcTemplate(); //jdbcTemplate.setDataSource(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.execute("create table user (id int primary key auto_increment,name varchar(20))"); } }
<?xml version="1.0" encoding="UTF-8"?> <!-- 引入beans的头 --> <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"> <!-- 配置Spring默认的连接池 --> <!-- 这个类由Spring来帮我们创建,它默认情况下只创建一次,因为是单例的. --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring3_day02"></property> <property name="username" value="root"></property> <property name="password" value=""></property> </bean> <!-- 配置DBCP连接池 --> <bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring3_day02"></property> <property name="username" value="root"></property> <property name="password" value=""></property> </bean> <!-- 定义jdbctemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource1"></property><!-- 把上面定义好的连接池注入进来了 --> </bean> </beans>