DBCP( 二) DataBase Connection Pool 的使用

使用DBCP必须用的三个包:

commons-dbcp-1.2.1.jar, commons-pool-1.2.jar, commons-collections-3.1.jar。

配置参数。

Java API: BasicDataSourceFactory.createDataSource(properties);

 

 

 

package cn.itcast.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import cn.itcast.jdbc.datasource.MyDataSource2;


public final class JdbcUtils {
    private static String url = "jdbc:mysql://localhost:3306/jdbc";
    private static String user = "root";
    private static String password = "";
    private static DataSource myDataSource = null;

    private JdbcUtils() {
    }

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // myDataSource = new MyDataSource2();
            Properties prop = new Properties();
            // prop.setProperty("driverClassName", "com.mysql.jdbc.Driver");
            // prop.setProperty("user", "user");

            InputStream is = JdbcUtils.class.getClassLoader()
                    .getResourceAsStream("dbcpconfig.properties");
            prop.load(is);
            myDataSource = BasicDataSourceFactory.createDataSource(prop);//工厂模式,创建数据源
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static DataSource getDataSource() {
        return myDataSource;
    }

    public static Connection getConnection() throws SQLException {
        // return DriverManager.getConnection(url, user, password);
        return myDataSource.getConnection();
    }

    public static void free(ResultSet rs, Statement st, Connection conn) {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (st != null)
                    st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (conn != null)
                    try {
                        conn.close();
                        // myDataSource.free(conn);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }
    }
}

posted @ 2013-12-09 00:04  剑握在手  阅读(422)  评论(0编辑  收藏  举报
返回顶部↑