直接上代码:
要引入jar包:
然后写xml文件:
<?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&characterEncoding=UTF8</property> </default-config> </c3p0-config>
bean层:
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层:
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 } }
发现同DBUtils比正常的dao要简单得多,代码量比较少
servlet层
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("message", "遍历成功"); request.getRequestDispatcher("list.jsp").forward(request, response); }else { request.setAttribute("message", "遍历失败,即将返回主页"); 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("message", "删除成功"); request.getRequestDispatcher("index.jsp").forward(request, response); }else { request.setAttribute("message", "删除失败,即将返回主页"); 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("message", "添加失败,即将返回主页"); 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("message", "修改成功"); request.getRequestDispatcher("index.jsp").forward(request, response); }else { request.setAttribute("message", "修改失败,即将返回主页"); 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>(); // 直接可以获取一个连接池 public static DataSource getDataSource() { return dataSource; } public static Connection getConnection() throws SQLException{ return dataSource.getConnection(); } // 获取连接对象 public static Connection getCurrentConnection() throws SQLException { Connection con = tl.get(); if (con == null) { con = dataSource.getConnection(); tl.set(con); } return con; } // 开启事务 public static void startTransaction() throws SQLException { Connection con = getCurrentConnection(); if (con != null) { con.setAutoCommit(false); } } // 事务回滚 public static void rollback() throws SQLException { Connection con = getCurrentConnection(); if (con != null) { con.rollback(); } } // 提交并且 关闭资源及从ThreadLocall中释放 public static void commitAndRelease() throws SQLException { Connection con = getCurrentConnection(); if (con != null) { con.commit(); // 事务提交 con.close();// 关闭资源 tl.remove();// 从线程绑定中移除 } } // 关闭资源方法 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(); } } }
与之前的增删改查相比 代码量减少了很多,进而在有限的时间写出更多的功能,进行更多的操作。
大家可以看我之前的简单的增删改查,真的代码量很多。
但是我也遇到了乱码的问题,向数据库中写的中文全是乱码,曾经测试过,发现写入servelt层和dao层都不是乱码,所以感觉是数据库出了问题,因此百度,发现了上述xml文件中数据库名字后面的限制,但是应该注意&在xml文件中编译不通过,所以要用转义字符&但是即使这样在之前的测试中还是乱码,问了同学发现,要改数据库的时区,因此在这中条件下终于成功了。
测试结果:
因为之前有乱码所以写的全是中文来测试。