1.C3P0
C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。
C3P0常用包下载地址:
链接:https://pan.baidu.com/s/18RSPWJ8NDgeOiXzY-WJlxg 密码:42x3
下面是基本的实现步骤:
创建一个配置文件db.proerties:
jdbc.user=root
jdbc.password=
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/bookstorejdbc.initialPoolSize=5
jdbc.maxPoolSize=10
声明一个applicationContext.xml文件:
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置C3P0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value=""></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
使用该数据库配置:
private ApplicationContext ctx=null;
ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource=ctx.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
2.Spring自带的JDBC
需导入文件:spring-jdbc-5.0.8.RELEASE.jar
db.protities文件:
url=jdbc:mysql://localhost:3306/test
driverClassName=com.mysql.jdbc.Driver
username=root
password=
bean配置:
<context:property-placeholder location="db.protities"/>
<bean id="dataSource" name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${driverClassName}" p:url="${url}" p:username="root" p:password="" />
测试:
ApplicationContext ctx=new ClassPathXmlApplicationContext("beansql.xml");
DataSource dataSource=(DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());