常用开源数据库连接池与编写自己的JDBC框架

本文介绍了常用的开源数据库连接池,如DBCP的配置细节,包括连接设置、初始化连接、最大和最小连接数以及超时设置。同时提到了C3P0的配置文件c3p0-config.xml的使用,并概述了Tomcat数据库连接池的配置。最后,文章探讨了如何编写自己的JDBC框架,利用元数据进行操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常用开源数据库连接池

数据库连接池都要实现DataSource接口

DBCP:

连接设置

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

初始化连接

initialSize=10

最大连接数量

maxActive=50

最大空闲连接

maxIdle=20

最小空闲连接

minIdle=5

超时等待时间以毫秒为单位 6000毫秒/1000等于60秒

maxWait=60000

JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]

注意:”user” 与 “password” 两个属性会被明确地传递,因此这里不需要包含他们。

connectionProperties=useUnicode=true;characterEncoding=utf8

指定由连接池所创建的连接的自动提交(auto-commit)状态。

defaultAutoCommit=true

driver default 指定由连接池所创建的连接的只读(read-only)状态。

如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)

defaultReadOnly=

driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。

可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE

defaultTransactionIsolation=READ_COMMITTED

    private static DataSource ds=null;
    static{
        try{ 
            InputStream in=JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties prop=new Properties();
            prop.load(in);
            BasicDataSourceFactory factory=new BasicDataSourceFactory();
            ds=factory.createDataSource(prop);
        }catch(Exception e){
            throw new ExceptionInInitializerError(e);
        }
    }
    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }

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://localhost:3306/day16</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>


    </default-config>

    <named-config name="yjw">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day16</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </named-config>

</c3p0-config>

使用方法:

    private static ComboPooledDataSource ds = null;
    static{
        try{
            ds = new ComboPooledDataSource();
        }catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }

Jndi容器

Tomcat数据库连接池:

配置文件:

<Context>
     <Resource name="jdbc/EmployeeDB" auth="Container"
            type="javax.sql.DataSource"
            username="root"
            password="root"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/day16"
            initialSize="10"
            maxActive="30"
            maxIdle="4"/>
</Context>

不要忘记将数据库驱动JAR包加入到Tomcat的lib目录中
使用方法:

    private static DataSource ds;
    static {
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }

编写自己的JDBC框架

元数据:数据库,表,列的定义信息。
Connection.getDatabaseMetaData();

PreparedStatement.getParameterMetaData();//获得代表PreparedStatement元数据的ParameterMetaData对象

ResultSet.getMetaData();//获得代表ResultSet对象元数据的ResultSetMetaData对象。


public class JdbcUtils {

    private static DataSource ds = null;
    static{
        try{
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties prop = new Properties();
            prop.load(in);
            BasicDataSourceFactory factory = new BasicDataSourceFactory();
            ds = factory.createDataSource(prop);
        }catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }


    public static void release(Connection conn,Statement st,ResultSet rs){

        if(rs!=null){
            try{
                rs.close();   //throw new 
            }catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;
        }
        if(st!=null){
            try{
                st.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
            st = null;
        }
        if(conn!=null){
            try{
                conn.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //String sql = "insert into account(id,name,money) values(?,?,?)"   object[]{1,"aaa","10000"};
    public static void update(String sql,Object params[]) throws SQLException{
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try{
            conn = getConnection();
            st = conn.prepareStatement(sql);
            for(int i=0;i<params.length;i++){
                st.setObject(i+1,params[i]);
            }
            st.executeUpdate();
        }finally{
            release(conn, st, rs);
        }
    }

    //
    public static Object query(String sql,Object params[],ResultSetHandler handler) throws SQLException{
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try{
            conn = getConnection();
            st = conn.prepareStatement(sql);
            for(int i=0;i<params.length;i++){
                st.setObject(i+1,params[i]);
            }
            rs = st.executeQuery();
            return handler.handler(rs);
        }finally{
            release(conn, st, rs);
        }
    }
}   

interface ResultSetHandler{
    public Object handler(ResultSet rs);
}


class BeanHandler implements ResultSetHandler{

    private Class clazz;
    public BeanHandler(Class clazz){
        this.clazz = clazz;
    }

    public Object handler(ResultSet rs) {
        try{
            if(!rs.next()){
                return null;
            }

            //创建封装结果集的bean
            Object bean = clazz.newInstance();

            //得到结果集的元数据,以获取结果集的信息
            ResultSetMetaData meta = rs.getMetaData();
            int count = meta.getColumnCount();
            for(int i=0;i<count;i++){
                String name = meta.getColumnName(i+1);   //获取到结果集每列的列名  id
                Object value = rs.getObject(name);     //1

                //反射出bean上与列名相应的属性
                Field f = bean.getClass().getDeclaredField(name);
                f.setAccessible(true);
                f.set(bean, value);
            }

            return bean;

        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

class BeanListHandler implements ResultSetHandler{

    private Class clazz;
    public BeanListHandler(Class clazz){
        this.clazz = clazz;
    }
    public Object handler(ResultSet rs) {
        List list = new ArrayList();
        try{
            while(rs.next()){
                Object bean = clazz.newInstance();
                ResultSetMetaData  meta = rs.getMetaData();
                int count = meta.getColumnCount();
                for(int i=0;i<count;i++){
                    String name = meta.getColumnName(i+1);
                    Object value = rs.getObject(name);

                    Field f = bean.getClass().getDeclaredField(name);
                    f.setAccessible(true);
                    f.set(bean, value);
                }
                list.add(bean);
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
        return list;

    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值