JDBC连接池:自定义连接池代码实现

JDBC连接和释放资源代码:

package cn.itheima.jdbc.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 提供获取连接和释放资源的 方法
 * 
 */
public class JDBCUtils_V3 {

    /**
     * 获取连接方法
     * 
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web08", "root", "ao1221");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

properties配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/web08?useUnicode=true&characterEncoding=utf8
username=root
password=ao1221

自定义连接池代码:

package cn.itheima.jdbc.DataSource;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;

import javax.sql.DataSource;

import cn.itheima.jdbc.utils.JDBCUtils_V3;

public class MyDataSource implements DataSource{
    //1.创建1个容器用于存储Connection对象
    private static LinkedList pool = new LinkedList();

    //2.创建5个连接放到容器中去
    static {
        for (int i = 0; i < 5; i++) {
            Connection conn = JDBCUtils_V3.getConnection();
            pool.add(conn);
        }
    }


    /**
     * 重写获取连接的方法
     */
    @Override
    public Connection getConnection() throws SQLException {
        Connection conn=null;
        //3.使用前先判断
        if(pool.size()==0) {
            //4.池子里面没有,我们再创建一些
            for (int i = 0; i < 5; i++) {
                conn = JDBCUtils_V3.getConnection();
                pool.add(conn);
            }
        }
        //5.从池子里面获取一个连接对象Connection
        conn = pool.remove(0);
        return conn;
    }

    /**
     * 归还连接对象到连接池中去
     */
    public void backConnection(Connection conn) {
        pool.add(conn);
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        // TODO Auto-generated method stub

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        // TODO Auto-generated method stub

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public  T unwrap(Class iface) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isWrapperFor(Class iface) throws SQLException {
        // TODO Auto-generated method stub
        return false;
    }



    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

}

测试代码:

package cn.itheima.jdbc.test;

import java.sql.Connection;
import java.sql.PreparedStatement;

import org.junit.Test;

import cn.itheima.jdbc.DataSource.MyDataSource;

public class TestMyDataSource {

    @Test
    public void testAddUser() {
        Connection conn=null;
        PreparedStatement pstmt = null;
        //1.创建自定义连接池对象
        MyDataSource dataSource = new MyDataSource();
        try {
            //2.从池子中获取连接
            conn=dataSource.getConnection();
            String sql = "insert into tbl_user values(null,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "吕布");
            pstmt.setString(2, "貂蝉");
            int rows = pstmt.executeUpdate();
            if(rows>0) {
                System.out.println("添加成功!");
            }else {
                System.out.println("添加失败!");
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            dataSource.backConnection(conn);
        }
    }

}

运行结果:
JDBC连接池:自定义连接池代码实现_第1张图片
JDBC连接池:自定义连接池代码实现_第2张图片

你可能感兴趣的:(Java必知必会,MySql)