Use dbutils c3p0 connection and a simple database CRUD operations

Directly on the code:

Jar package to be introduced:

 

 Then write xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <default-config>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///db13?serverTimezone=UTC&amp;characterEncoding=UTF8</property>
    </default-config> 
</c3p0-config> 

 

bean layer:

package com.user.bean;

public class Bean {
    private String name;
    private String id;
    private String sex;
    
    public Bean(String name, String id, String sex) {
        super();
        this.name = name;
        this.id = id;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Bean() {
        // TODO Auto-generated constructor stub
    }

}

dao layer:

package com.user.dao;

import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.user.bean.Bean;
import com.user.utils.DBUtils;

public class Dao {
    
    public  static boolean insertUser(Bean b) {
        System.out.println(b.getSex());
        QueryRunner qr=new QueryRunner(DBUtils.getDataSource());
        String sql="insert into user values(?,?,?)";
        try {
            int i=qr.update(sql,b.getName(),b.getId(),b.getSex());
            if(i>0) return true;
            else return false;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    } 
    public  static boolean updateUser(Bean b) {
        QueryRunner qr=new QueryRunner(DBUtils.getDataSource());
        String sql="update user set name=?,sex=? where id=?";
        try {
            int i=qr.update(sql,b.getName(),b.getSex(),b.getId());
            if(i>0) return true;
            else return false;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
        
    } 
    
    
    public  static boolean deleteUser(Bean b) {
        QueryRunner qr=new QueryRunner(DBUtils.getDataSource());
        String sql="delete from user where id=?";
        try {
            int i=qr.update(sql,b.getId());
            if(i>0) return true;
            else return false;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
        
    } 
    
    public  static List<Bean> queryUser() {
        QueryRunner qr=new QueryRunner(DBUtils.getDataSource());
        String sql="select * from user";
        try {
            List<Bean> list =qr.query(sql, new BeanListHandler<Bean>(Bean.class));
            return list;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    } 
    
    
    public Dao() {
        // TODO Auto-generated constructor stub
    }

}

Found that much simpler with DBUtils than normal dao, less than the code

servlet layer

package com.user.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.user.bean.Bean;
import com.user.dao.Dao;

/**
 * Servlet implementation class servlet
 */
@WebServlet("/servlet")
public class servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
//        response.getWriter().append("Served at: ").append(request.getContextPath());
        response.setCharacterEncoding("UTF-8");
        String method =request.getParameter("method");
        if("update".equals(method)) {
            try {
                update(request,response);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else if("insert".equals(method)) {
            try {
                insert(request,response);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else if("delete".equals(method)) {
            try {
                delete(request,response);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else if("list".equals(method)) {
            try {
                list(request,response);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("UTF-8");
        List<Bean> list =Dao.queryUser();
        request.setAttribute("list", list);
        if(!list.isEmpty()) {
            request.setAttribute ( "the Message", "traverse success" );
            request.getRequestDispatcher("list.jsp").forward(request, response);
        }else {
            request.setAttribute ( "the Message", "traverse failed, about to return to home page" );
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
        
        
        
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("UTF-8");
        String name=request.getParameter("name");
        String id=request.getParameter("id");
        String sex=request.getParameter("sex");
        Bean b=new Bean();
        b.setName(name);
        b.setId(id);
        b.setSex(sex);
        if(Dao.deleteUser(b)) {
            request.setAttribute ( "the Message", "deleted successfully" );
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }else {
            request.setAttribute ( "the Message", "delete failed, about to return to home page" );
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }

    private void insert(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        String name=request.getParameter("name");
        String id=request.getParameter("id");
        String sex=request.getParameter("sex");
        System.out.println(name+id+sex);
        Bean b=new Bean(name,id,sex);
        if(Dao.insertUser(b)) {
            request.setAttribute("message", "添加成功");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }else {
            request.setAttribute ( "the Message", "add failed, about to return to home page" );
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
        
    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("UTF-8");
        String name=request.getParameter("name");
        String id=request.getParameter("id");
        String sex=request.getParameter("sex");
        Bean b=new Bean();
        b.setName(name);
        b.setId(id);
        b.setSex(sex);
        if(Dao.updateUser(b)){
            request.setAttribute ( "the Message", "modified successfully" );
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }else {
            request.setAttribute ( "the Message", "modification failed, about to return to home page" );
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

}

 

dbutil:

package com.user.utils;

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

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public  class dbUtils {

    private static DataSource dataSource = new ComboPooledDataSource();

    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    // can be directly connected to obtain a pool of 
    public  static the DataSource getDataSource () {
         return the dataSource;
    }
    
    public static Connection getConnection() throws SQLException{
        return dataSource.getConnection();
    }

    // Get the connection object 
    public  static Connection getCurrentConnection () throws SQLException {

        Connection con = tl.get();
        if (con == null) {
            con = dataSource.getConnection();
            tl.set (with);
        }
        return con;
    }

    // open affairs 
    public  static  void startTransaction () throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.setAutoCommit(false);
        }
    }

    // transaction rollback 
    public  static  void ROLLBACK () throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.rollback();
        }
    }

    // Submit and closing and releasing resources from the ThreadLocall 
    public  static  void commitAndRelease () throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.commit (); // transaction commits 
            con.close (); // close the resource 
            tl.remove (); // remove from the thread binding 
        }
    }

    // Close the resource method 
    public  static  void closeConnection () throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.close();
        }
    }

    public static void closeStatement(Statement st) throws SQLException {
        if (st != null) {
            st.close();
        }
    }

    public static void closeResultSet(ResultSet rs) throws SQLException {
        if (rs != null) {
            rs.close();
        }
    }
}

 

 

 

Change compared with the previous additions check code amount reduced a lot, in turn write more features for a limited time, for more operations.

You can look simple additions and deletions to change search before me, really a lot of code amount.

But I also encountered garbled question, write to the database in Chinese all garbled, have tested and found written servelt dao layer and the layer is not garbled, so the feeling is that the database is a problem, therefore Baidu, we found above xml file database limit behind the name, but it should be noted that & in the xml file compiler is not passed, so use an escape character & amp; but even so before the test or distortion, asked the students found to change the time zone database, Therefore, in this conditional finally succeeded.

Test Results:

Because there are so garbled before all written in Chinese test.

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/tkg1314/p/12120218.html