简单的数据库增删改查实现 (自我理解)

首先

需要的jar 包:

 

 

 

 

堆代码:

User类

 1 /**
 2  * 创建存储基本信息
 3  * @author cuixingyu
 4  *
 5  */
 6 
 7 public class User {
 8     private String name;
 9     private String age;
10     private String sex;
11     public String getName() {
12         return name;
13     }
14     public void setName(String name) {
15         this.name = name;
16     }
17     public String getAge() {
18         return age;
19     }
20     public void setAge(String age) {
21         this.age = age;
22     }
23     public String getSex() {
24         return sex;
25     }
26     public void setSex(String sex) {
27         this.sex = sex;
28     }
29     public User(String name, String age, String sex) {
30         super();
31         this.name = name;
32         this.age = age;
33         this.sex = sex;
34     }
35     
36 
37 }

 

然后为DBUtil 类  :建立对数据库的连接 和提供关闭状态和连接的函数

  1 /**
  2  * 测试时主要要导入jar 包
  3  */
  4 
  5 import java.beans.Statement;
  6 import java.sql.Connection;
  7 import java.sql.DriverManager;
  8 import java.sql.PreparedStatement;
  9 import java.sql.ResultSet;
 10 import java.sql.SQLException;
 11 
 12 /**
 13  * 建立数据库连接
 14  * @author cuixingyu
 15  *
 16  */
 17 public class DBUtil {
 18     // 连接数据库 url路径和用户名 密码
 19     public static String db_url="jdbc:mysql://localhost:3306/db_database01?serverTimezone=UTC&characterEncoding=UTF-8&useSSL=false";
 20     public static String db_user="root";
 21     public static String db_password="101032";
 22     public static Connection getConn()  {
 23         Connection conn=null;
 24         try {
 25             // 数据库驱动加载
 26             Class.forName("com.mysql.cj.jdbc.Driver");
 27             try {
 28                 //链接数据库
 29                 conn=DriverManager.getConnection(db_url, db_user, db_password);
 30             } catch (SQLException e) {
 31                 // TODO Auto-generated catch block
 32                 e.printStackTrace();
 33             }
 34             System.out.println("驱动链接加载成功!");
 35         } catch (ClassNotFoundException e) {
 36             // TODO Auto-generated catch block
 37             e.printStackTrace();
 38         }
 39         //返回链接
 40         return conn;
 41         
 42     }
 43     
 44     //关闭函数
 45     public static void close(Statement state,Connection conn) {
 46         //只有状态和连接时,先关闭状态
 47         if(state!=null) {
 48             try {
 49                 ((Connection) state).close();
 50             } catch (SQLException e) {
 51                 // TODO Auto-generated catch block
 52                 e.printStackTrace();
 53             }
 54 
 55             
 56         }
 57         if(conn!=null) {
 58             try {
 59                 conn.close();
 60             } catch (SQLException e) {
 61                 // TODO Auto-generated catch block
 62                 e.printStackTrace();
 63             }
 64         }
 65     }
 66     //关闭函数
 67     public static void close(PreparedStatement state,Connection conn) {
 68         if(state!=null) {
 69             try {
 70                 ((Connection) state).close();
 71             } catch (SQLException e) {
 72                 // TODO Auto-generated catch block
 73                 e.printStackTrace();
 74             }
 75             
 76         }
 77         if(conn!=null) {
 78             try {
 79                 conn.close();
 80             } catch (SQLException e) {
 81                 // TODO Auto-generated catch block
 82                 e.printStackTrace();
 83             }
 84         }
 85     }
 86     
 87     public static void close(ResultSet rs,Statement state,Connection conn) {
 88         if(rs!=null) {
 89             try {
 90                 rs.close();
 91             } catch (SQLException e) {
 92                 // TODO Auto-generated catch block
 93                 e.printStackTrace();
 94             }
 95         }
 96         if(state!=null) {
 97             try {
 98                 ((Connection) state).close();
 99             } catch (SQLException e) {
100                 // TODO Auto-generated catch block
101                 e.printStackTrace();
102             }
103         }
104         if(conn!=null) {
105             try {
106                 conn.close();
107             } catch (SQLException e) {
108                 // TODO Auto-generated catch block
109                 e.printStackTrace();
110             }
111         }
112     }
113 
114   //关闭函数 
115     public static void close(java.sql.Statement state, Connection conn) {
116         // TODO Auto-generated method stub
117         if(state!=null)
118         {
119             try {
120                 state.close();
121             } catch (SQLException e) {
122                 // TODO Auto-generated catch block
123                 e.printStackTrace();
124             }
125         }
126         if(conn!=null) {
127             try {
128                 conn.close();
129             } catch (SQLException e) {
130                 // TODO Auto-generated catch block
131                 e.printStackTrace();
132             }
133         }
134     }
135     //测试主函数  利用Java运行来测试
136     @SuppressWarnings("static-access")
137     public static void main(String[] args) throws SQLException {
138         DBUtil dbu=new DBUtil();
139         dbu.getConn();
140     }
141 }

 

Dao类: 使用sql 语句对数据进行增删改查的操作

  1     
  2     //遍  历  使用list函数进行遍历
  3     public static List<User> show() {
  4         //构建遍历函数
  5         List<User>list =new ArrayList<>();
  6         //建立数据库链接
  7         Connection conn=DBUtil.getConn();
  8         //sql 语句 查询
  9         String sql="select * from tb_userinfo";
 10         Statement pstmt = null;
 11         try {
 12             //执行sql语句
 13             pstmt = conn.createStatement();
 14             ResultSet rs=pstmt.executeQuery(sql);
 15             User use=null;
 16             while(rs.next()) {
 17                 //遍历获取的信息
 18                 String name=rs.getString("name");
 19                 String age=rs.getString("age");
 20                 String sex=rs.getString("sex");
 21                 use=new User(name,age,sex);
 22                 list.add(use);
 23             }
 24         } catch (SQLException e) {
 25             // TODO Auto-generated catch block
 26             e.printStackTrace();
 27         }
 28         finally {
 29             DBUtil.close(pstmt, conn);
 30             }
 31         
 32         return list;
 33         }
 34     
 35     //添加
 36     public static boolean insert(User e) {
 37         System.out.println("添加中");
 38         //sql语句
 39         String sql="insert into tb_userinfo(name,age,sex) values('"+e.getName()+"','"+e.getAge()+"','"+e.getSex()+"')";
 40         //链接建立
 41         Connection conn=DBUtil.getConn();
 42         Statement state=null;
 43         
 44         try {
 45             //执行sql语句
 46             state= conn.createStatement();
 47             state.executeUpdate(sql);
 48         } catch (SQLException e1) {
 49             // TODO Auto-generated catch block
 50             e1.printStackTrace();
 51         }
 52         finally {
 53             //关闭状态和连接
 54             DBUtil.close(state, conn);
 55         }
 56         return false;
 57         
 58     }
 59     
 60     //删除 按照姓名
 61     public static boolean delete(String name) {
 62         //按姓名删除 sql语句
 63         String sql="delete from tb_userinfo where name='"+name+"'"  ;
 64         Connection conn=DBUtil.getConn();
 65         Statement pstm=null;
 66         try {
 67             pstm=conn.createStatement();
 68             pstm.executeUpdate(sql);
 69         } catch (SQLException e) {
 70             // TODO Auto-generated catch block
 71             e.printStackTrace();
 72         }
 73         finally {
 74             //关闭连接与状态
 75             DBUtil.close(pstm, conn);
 76         }
 77         
 78         return false;
 79     }
 80     
 81     //修改
 82     public static boolean update(User e) {
 83         System.out.println("修改中");
 84         // sql 语句 按照姓名修改
 85         String sql="update tb_userinfo set name='"+e.getName()+"',age='"+e.getAge()+"',sex='"+e.getSex()+"'   where name='"+e.getName()+"' ";
 86         Connection conn=DBUtil.getConn();
 87         Statement pstm=null;
 88         try {
 89             pstm=conn.createStatement();
 90             pstm.executeUpdate(sql);
 91         } catch (SQLException e1) {
 92             // TODO Auto-generated catch block
 93             e1.printStackTrace();
 94         }finally{
 95             //关闭状态和连接
 96             DBUtil.close(pstm, conn);
 97             }
 98         return false;
 99         
100     }
101     
102     //主函数  测试数据库增删改查
103     public static void main(String[] args) {
104         //User a=new User("cxt","25","男");
105         /*insert(a);*/
106         //User b=new User("cxt","12","女");
107         /*update(b);*/
108         List<User> list=show();
109         for(int i=0;i<list.size();i++) {
110             User e=list.get(i);
111             System.out.println(e.getName()+" "+e.getSex()+" "+e.getAge());
112         }
113         /*String name="cxt";*/
114         /*delete(name);*/
115     }
116 
117 }

 

Servlet 类: 实现前端和后台的数据交互

 1  2 
 3 import java.util.List;
 4 import com.Bean.User;
 5 import com.Dao.dao;
 6 
 7 public class service {
 8     dao im=new dao();
 9     public boolean insert(User e) { //添加
10         dao.insert(e);
11         System.out.println("Service dao层添加");
12         return true;
13     }
14     public List<User> show() {  //展示
15         System.out.println("Service 层展示");
16         return dao.show();
17         }
18     
19     public void update(User e) { //修改
20         System.out.println("Service 修改");
21         dao.update(e);
22     }
23     public void delete(String name) { //删除
24         dao.delete(name);
25     }
26 
27 }
  1 import java.io.IOException;
  2 import java.io.UnsupportedEncodingException;
  3 import java.util.List;
  4 
  5 import javax.servlet.ServletException;
  6 import javax.servlet.annotation.WebServlet;
  7 import javax.servlet.http.HttpServlet;
  8 import javax.servlet.http.HttpServletRequest;
  9 import javax.servlet.http.HttpServletResponse;
 10 
 11 import com.Bean.User;
 12 import com.mysql.cj.x.protobuf.MysqlxCrud.Delete;
 13 
 14 /**
 15  * Servlet implementation class Servlet
 16  */
 17 @WebServlet("/Servlet")
 18 public class Servlet extends HttpServlet {
 19     private static final long serialVersionUID = 1L;
 20     
 21     //创建一个service 
 22     service service= new service();
 23        
 24     //根据前台获取的数据决定执行具体操作
 25     protected void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
 26         
 27         req.setCharacterEncoding("utf-8");
 28         //获取前台 通过 method 传递过来的参数数据
 29         String method=req.getParameter("method");
 30         //根据传过来的数据执行相应的操作
 31         if("insert".equalsIgnoreCase(method)) {
 32             insert(req,resp);
 33         }else if("update".equals(method)) {
 34             update(req,resp);
 35         }else if("delete".equals(method)) {
 36             Delete(req,resp);
 37         }
 38         else if("show".equals(method)) {
 39             show(req,resp);
 40          }
 41     }
 42         
 43     //遍历 数据库内的信息
 44 
 45     private void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  {
 46         // TODO Auto-generated method stub
 47         //编码方式为 utf-8 避免乱码
 48         req.setCharacterEncoding("utf-8");
 49         //将数据传递到 list 数组中
 50         List<User> list= service.show();
 51         // 将后一属性的值传递给后一个
 52         req.setAttribute("list", list);
 53         //将 前一个list 传递到show.jsp 并进行遍历输出  
 54         req.getRequestDispatcher("show.jsp").forward(req, resp);
 55         
 56     }
 57 
 58 
 59    //删除数据库内的数据  按照姓名删除
 60     private void Delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 61         // TODO Auto-generated method stub
 62         //编码方式为 utf-8 避免乱码
 63         req.setCharacterEncoding("utf-8");
 64         //获取需要删除的姓名
 65         String name=req.getParameter("name");
 66         //执行删除操作
 67         service.delete(name);
 68         //执行完之后 跳转到 遍历的界面 显示删除后的结果
 69         req.getRequestDispatcher("Servlet?method=show").forward(req, resp);
 70         
 71     }
 72  
 73      // 按姓名 修改个人信息
 74     private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
 75         // TODO Auto-generated method stub
 76         //编码方式为 utf-8 避免乱码
 77         req.setCharacterEncoding("utf-8");
 78         //获取jsp 传递过来的数据信息
 79         String name=req.getParameter("name");
 80         String age=req.getParameter("age");
 81         String sex=req.getParameter("sex");
 82         System.out.println(sex);
 83         // 修改的传参调用的是 User 类 ,创建一个新的User 进行操作
 84         User use=new User(name,age,sex);
 85         System.out.println(use.getSex());
 86         System.out.println("servlet 修改");
 87         //执行修改操作
 88         service.update(use);
 89         //跳转到遍历界面 显示修改后的信息
 90         req.getRequestDispatcher("Servlet?method=show").forward(req, resp);
 91         
 92     }
 93    
 94     //添加 新的信息
 95     private void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 96         // TODO Auto-generated method stub
 97         //  设置编码为Utf-8 避免乱码
 98         req.setCharacterEncoding("utf-8");
 99         ////获取jsp 传递过来的数据信息
100         String name=req.getParameter("name");
101         String age=req.getParameter("age");
102         String sex=req.getParameter("sex");
103         //构建新的User 类 执行添加操作
104         User use= new User(name,age,sex);
105         service.insert(use);
106         //添加完成跳转到主界面
107         req.getRequestDispatcher("main.jsp").forward(req, resp);
108     }
109 
110 }

 

jsp 代码:

main 主界面:

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <!--     使用jstl-1.2.jar 包的语句 -->
 4     <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 5 <!DOCTYPE html>
 6 <html>
 7 <head>
 8 <meta charset="utf-8">
 9 <title>主界面</title>
10 </head>
11 <body>
12 <div align="center">
13 <h1 >信息管理</h1>
14  <div >
15 <!--  跳转到各个操作界面 -->
16    <a href="add.jsp">添加</a>
17  </div>
18   <div >
19    <a href="update.jsp">修改</a>
20  </div>
21   <div >
22    <a href="delete.jsp">删除</a>
23  </div>
24   <div >
25    <a href="show.jsp">遍历</a>
26  </div>
27  
28 </div>
29 
30 </body>
31 </html>

add 添加界面:

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3    
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="utf-8">
 8 <title>添加</title>
 9 </head>
10 <body>
11 <div align="center">
12 <h1> 添加信息:</h1>
13 <a href="main.jsp">返回</a>
14 <form action="Servlet?method=insert" method="post" onsubmit="return check()">
15 <div >
16 姓名<input type="text" id="name" name="name">
17 </div>
18 <div >
19 年龄<input type="text" id="age" name="age">
20 </div>
21 <div >
22 性别<input type="text" id="sex" name="sex">
23 </div>
24 
25 <div >
26 <button type="submit" >添加</button>
27 </div>
28 </form>
29 </div>
30 <!--   目前没有作用,如果要对输入的数据进行限制则需要使用 -->
31 <script type="text/javascript">
32 function check(){
33     var name = document.getElementById("id");
34     var age  = document.getElementById("age");
35     var sex  = document.getElementById("sex");
36 }
37 </script>
38 
39 
40 </body>
41 </html>

show 遍历界面:

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3     <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="utf-8">
 8 <title>遍历</title>
 9 </head>
10 <body>
11 <div align="center">
12 <h1>信息:</h1>
13 <a href="main.jsp">返回</a>
14 <form action="Servlet?method=show" method="post" onsubmit="return check()">
15 <button type="submit"> 展示</button>
16 <table>
17 <tr>
18 <td>姓名</td>
19 <td>年龄</td>
20 <td>性别</td>
21 </tr>
22 <!--   html 中 for循环语句    list 是由Servlet中的show 传过来的第一个list    -->
23 <c:forEach items="${list}" var="item">
24 <!-- var 定义变量, 给 items 重命名 -->
25 <tr>
26  <td>${item.name}</td>
27  <td>${item.age}</td>
28  <td>${item.sex}</td>
29 </tr>
30 </c:forEach>
31 </table>
32 </form>
33 </div>
34 
35 </body>
36 </html>

update 修改界面:

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3     <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="utf-8">
 8 <title>修改</title>
 9 </head>
10 <body>
11 <div align="center">
12 <h1> 修改信息</h1>
13 <a href="main.jsp">返回</a>
14 <form action="Servlet?method=update" method="post" onsubmit="return check()">
15 <div>
16 姓名<input type="text" id="name" name="name"  >
17 </div>
18 <div>
19 年龄<input type="text" id="age" name="age" >
20 </div>
21 <div>
22 性别<input type="text" id="sex" name="sex" >
23 </div>
24 <div>
25 <button type="submit" >修改</button>
26 </div>
27 </form>
28 </div>
29 
30 
31 <!-- 目前没有作用,如果需要对数据进行限制则需要使用该处数据 -->
32 <script type="text/javascript">
33 function check(){
34     var name=docment.getElementById("name");
35     var age=document.getElementById("age");
36     var sex=document.getElementById("sex");
37     }
38 </script>
39 
40 </body>
41 </html>

delete 删除界面:

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3     <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="utf-8">
 8 <title>修改</title>
 9 </head>
10 <body>
11 <div align="center">
12 <a href="main.jsp">返回</a>
13 <form action="Servlet?method=delete" method="post" onsubmit="return check()">
14 <div>
15 姓名<input type="text" id="name" name="name" placeholder="需要删除的姓名">
16 </div>
17 <div>
18 <button type="submit">提交</button>
19 </div>
20 </form>
21 </div>
22 <script type="text/javascript">
23 function check() {
24     var name=document.getElementById("name");
25     
26 }
27 </script>
28 
29 </body>
30 </html>

 

数据库如下:最好建一个id类进行计数并选择自动递增。

 

 

 

 

步骤(个人习惯):首先把Java类的 Bean层创建好,其次建立数据库的连接,并且通过主函数对连接进行检验,检测是否正常连接。

 其次建立Dao层,通过sql语句实现数据库的增删改查,每次实现一个具体类型时就要进行测试,即在主函数内建立一个Dao类,通过调用函数来观察数据库的变化是否符号要求。

建立Service 层,作为中介调用Dao层函数。 

建立Servlet层,实现前端与后台的数据交互。

最后实现前端界面,根据需求来制作界面,要熟读要求,不要以“我以为”的态度去架构前台,要站在用户角度来思考问题。

 

通过半个学期的摸索,对Java web的内部结构有了一个较为清晰的认识,写下来加深一下认识,肯定有不周全的地方,敬请多多包涵。

 

如果错误或问题,敬请指正。

不胜感激!

posted @ 2019-11-20 21:31  不懂就要问!  阅读(1745)  评论(0编辑  收藏  举报