一个无框架的数据库连接池

        最近在做一个项目,突然觉得数据库连接池的重要性,然后在网上各种百度、goolge,好多都是配置,起初我也迷恋上了配置,但我这项目里没用框架,配置也是可以的,但我最后也没有找到能在我项目里用的,有一种配置还是只能用tomcat来解析,意思是只能在jsp里用,对java compevn的研究后发现不可能,为了这我还加了java交流群,有个人说的挺好,我在main方法里想要用‘com evn’就好比在main直接调用js一样,最后我不再迷恋配置,还是手写了一下,在这里,我就说一下我的代码解析:

 

第一步:

web.xml里的配置:

<listener>

        <listener-class>cn.llhc.edu.servlet.MyListener</listener-class>

    </listener>

 

这主要是触发MyListener


第二步:

MyListener类:

publicclass MyListener implementsServletContextListener {

    private ServletContext context = null;

 

     publicvoidcontextDestroyed(ServletContextEvent event){

      //Output asimple message to the server's console

     System.out.println("The SimpleWeb App. Has Been Removed");

      this.context = null;

    }

     // 这个方法在Web应用服务做好接受请求的时候被调用。

  
   

web项目启动时,调用contextInitialized方法,在这里获取context对象,然后把创建好的连接池放到context对象里来共享

    publicvoidcontextInitialized(ServletContextEvent event){

      this.context =event.getServletContext();

      //Output asimple message to the server's console

      DBConnPool dbPool = new DBConnPool();

     dbPool.creatDbPool();

      System.out.println(dbPool);

      context.setAttribute("dbPool", dbPool);

     System.out.println("数据库连接池已建好,放了50个连接");

    }

 

    }

第三步:

DBConnPool

publicclass DBConnPool {

  
   

这个方法就是来创建连接的,然后把连接放到list

    publicLinkedList<Connection> list = null;//

    public DBConnPool(){}

    publicvoid creatDbPool(){

        try {

            Class.forName("com.mysql.jdbc.Driver");

            list = newLinkedList<Connection>();

            for (int i = 0; i < 50;i++) {

                Stringurl = "jdbc:mysql://localhost:3306/zongce?useUnicode=true&characterEncoding=utf-8";

                Connectionconn = DriverManager.getConnection(url,"root", "123");

                list.add(conn);

            }

           

           

        } catch (Exception e) {

            // TODO Auto-generatedcatch block

            e.printStackTrace();

        }

    }

  
   

这个方法就是来获取连接池里的一个连接

    publicsynchronized ConnectiongetOneConnetion(){

        if(list.size()>0){

            returnlist.removeFirst();

        }else{

            return null;

        }

    }

    publicsynchronizedvoidputBackOneConnetion(Connection conn){

        list.addLast(conn);

    }

  
   

这个方法就是来把用完之后的连接放回连接池中

   

}

 

 

以上三步做好了之后,就配置成功,接下来就来告一下怎么用它

 

  
   

在登录里面说一下怎么用它

publicclass LoginServlet extends HttpServlet {

  
   

先获取application对象,和前面的context是一个对象,然后再从它里面把数据库连接池拿出来。

    privatestaticfinallongserialVersionUID = 1L;

    protectedvoidservice(HttpServletRequest req, HttpServletResponse resp)

            throws ServletException,IOException {

        //post处理乱码  法1:

        req.setCharacterEncoding("utf-8");

        //获取session

        HttpSessionsession = req.getSession();

        ServletContextapplication = (ServletContext) session

        .getServletContext();

        DBConnPooldbPool = (DBConnPool) application.getAttribute("dbPool");

       

        //dao层的方法

        StudentDaosd = newStudentDaoImpl(dbPool);

        TeacherDaotd = newTeacherDaoImpl(dbPool);

        MenuDaomd = new MenuDaoImpl(dbPool);

       

  
   

在我的每个dao层的方法里都把dbPool给引了进去。

        //处理页面传过来的信息

        Stringrole = req.getParameter("role");

        Stringid = req.getParameter("id");

        Stringpassword = req.getParameter("password");

        System.out.println(role+".........");

 

再说说dao层里的类吧:

  
   

在这里写了个有参构造方法,把dbPool给引了进来,然后,下面方法里就可以用了。

  StudentDaoImpl 做个例子,大家举一反三:

publicclass StudentDaoImpl implements StudentDao{

    private DBConnPool dbPool = null;

    public StudentDaoImpl(){

       

    }

    publicStudentDaoImpl(DBConnPool pool){

        dbPool = pool;

    }

    @Override

    publicList<Student> findStudentsByClas(String clas) {//根据班号查找学生信息

        // TODO Auto-generatedmethod stub

        List<Student> users = newArrayList<Student>();

        Connectionconn = null;

        List<Connection>conns= dbPool.list;

        try {

            clas = "select *from t_student where fk_cla_id="+clas;

            if(conns==null||conns.size()==0)

                conn= Conn.getConn();//如果连接池里没有的话,创建一个,方便junit单元测试

            else

                conn= dbPool.getOneConnetion();

            ResultSet rs =conn.createStatement().executeQuery(clas);

           

//          ResultSet rs =Conn.getSql().executeQuery(clas);

            while(rs.next()){

                Studentuser = new Student();

  
   

在这里做了一个判断,如果连接池里有连接,就从中取,如果没有我就直接创建一个连接,这样也方便测试。

                user.setStudentId(rs.getString("pk_stu_id"));

                user.setStudentName(rs.getString("stu_name"));

                user.setClasId(rs.getString("fk_cla_id"));

                users.add(user);

  
   

最后一步大家不要忘了,记得把连接放回去

            }

        } catch (SQLException e){

            // TODO Auto-generatedcatch block

            e.printStackTrace();

        }finally{

                if(dbPool!=null)

                    dbPool.putBackOneConnetion(conn);

            }

        return users;

    }

 

希望对你有帮助

一个未毕业的IT志向男,大虾们可以多多指点,指出我里面不足的地方

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值