码迷,mamicode.com
首页 > 数据库 > 详细

[javaEE] 开源数据库连接池

时间:2016-07-09 11:53:58      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

一些开源组织提供了数据源的独立实现:

DBCP数据库连接池

C3P0数据库连接池

Apache Tomcat内置的连接池

 

DBCP连接池

apache提供的连接池实现,需要导入common-dbcp.jar commons-pool.jar

 

import java.io.FileReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPTest {
    public static void main(String[] args) throws Exception {
        //导入配置文件
        Properties prop=new Properties();
        prop.load(new FileReader("dbcp.properties"));
        //获取数据源
        BasicDataSourceFactory factory=new BasicDataSourceFactory();
        DataSource pool=factory.createDataSource(prop);
        
        Connection conn=pool.getConnection();
        //获取传输器对象
        Statement statement=conn.createStatement();
        //获取结果集对象
        ResultSet resultSet=statement.executeQuery("select * from user");
        //遍历
        while(resultSet.next()){
            String username=resultSet.getString("username");
            System.out.println(username);
        }
        //关闭资源
        resultSet.close();
        statement.close();
        conn.close();
        
    }
}

在项目目录下新建dacp.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///java
username=root
password=root

 

C3P0连接池

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBCPTest {
    public static void main(String[] args) throws Exception {
        //使用C3P0
        ComboPooledDataSource pool=new ComboPooledDataSource();
        Connection conn=pool.getConnection();
        //获取传输器对象
        Statement statement=conn.createStatement();
        //获取结果集对象
        ResultSet resultSet=statement.executeQuery("select * from user");
        //遍历
        while(resultSet.next()){
            String username=resultSet.getString("username");
            System.out.println(username);
        }
        //关闭资源
        resultSet.close();
        statement.close();
        conn.close();
        
    }
}

C3P0需要在类加载目录下新建c3p0-config.xml

<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///java</property>
        <property name="user">root</property>
        <property name="password">root</property>
    </default-config>
</c3p0-config>

 

 

[javaEE] 开源数据库连接池

标签:

原文地址:http://www.cnblogs.com/taoshihan/p/5655433.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!