一、所需要的jar包
c3p0.jar commons-logging.jar mysql-connector-java.jar spring3.0.jar spring3.0-source.jar
具体可参考项目ictclas4j中的lib文件夹。此处略。
二、使用类例子
1.dao文件
public class LabDao { private JdbcTemplate template; public void setDataSource(DataSource dataSource){ template = new JdbcTemplate(dataSource); } public void test(){ System.out.println("wei"); } private static ApplicationContext context = null; private static LabDao labDao = null; static{ context = new FileSystemXmlApplicationContext("config/beans-config.xml"); labDao = (LabDao) context.getBean("LabDao"); } private JdbcTemplate getTemplate(){ return template; } public static JdbcTemplate getJdbcTemplate(){ return labDao.getTemplate(); } public static void main(String[] args) { JdbcTemplate template = LabDao.getJdbcTemplate(); System.out.println(template.queryForInt("select count(1) from webinfo")); } }
2.配置文件beans-config.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" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- <context:property-placeholder location="jdbc.properties"/> --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/lab?useUnicode=true&characterEncoding=UTF-8"/> <property name="user" value="root"/> <property name="password" value="123456"/> <property name="minPoolSize" value="1"/> <property name="maxPoolSize" value="4"/> <property name="maxIdleTime" value="1800"/> <property name="acquireIncrement" value="2"/> <property name="maxStatements" value="0"/> <property name="initialPoolSize" value="2"/> <property name="idleConnectionTestPeriod" value="1800"/> <property name="acquireRetryAttempts" value="10000"/> <property name="breakAfterAcquireFailure" value="true"/> <property name="testConnectionOnCheckout" value="false"/> </bean> <bean id="LabDao" class="org.util.LabDao"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
Spring与c3p0建立数据库连接池,备忘录
最新推荐文章于 2024-09-19 21:52:00 发布