乐趣区

MVC模式实现数据库的增删改查

什么是 MVC 模式

MVC 模式中 M 代表模型、V 代表视图、C 代表控制器。
Model(模型)表示应用程序核心(比如数据库记录列表)。
View(视图)显示数据(数据库记录)。
Controller(控制器)处理输入(写入数据库记录)。

数据库设计

表名:student、使用的为 mysql 数据库

M 层

package cn.jdbc.domain;

public class student {
// 学号
private String sno;
// 姓名
private String sname;
// 年龄
private int sage;
public String getSno() {return sno;}
public void setSno(String sno) {this.sno = sno;}
public String getSname() {return sname;}
public void setSname(String sname) {this.sname = sname;}
public int getSage() {return sage;}
public void setSage(int sage) {this.sage = sage;}
}

V 层

jsp 页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> 学生数据 </title>
</head>
<body>
    <table border="1" border="1" cellpadding="0" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th> 学号 </th>
                <th> 姓名 </th>
                <th> 年龄 </th>
            </tr>
        </thead>
        <tbody>
             <c:forEach  items="${list}" var="i">
            <tr >
                   <td>${i.sno}</td>
                   <td>${i.sname}</td>
                   <td>${i.sage}</td>
            </tr>
            </c:forEach> 
        </tbody>
    </table>
    <form action="/sy3/display" method="post">
        <label> 查询的学号 </label>
        <input type="text" name="search_no" value="">
        <input type="submit" value="查询">
        <a href="http://localhost:9999/sy3/display"> 返回 </a><br>      
    </form>
    <h5> 添加数据 </h5>
    <form action="/sy3/display" method="post">
        <label> 学号 </label>
        <input type="text" name="add_sno" value="">
        <label> 姓名 </label>
        <input type="text" name="add_sname" value="">
        <label> 年龄 </label>
        <input type="text" name="add_sage" value="">                
        <input type="submit" value="添加">     
    </form>
    <h5> 修改数据 </h5>
    <form action="/sy3/display" method="post">
        <label> 学号 </label>
        <input type="text" name="cg_sno" value="">
        <label> 姓名 </label>
        <input type="text" name="cg_sname" value="">
        <label> 年龄 </label>
        <input type="text" name="cg_sage" value="">                
        <input type="submit" value="修改">     
    </form>
    <h5> 删除数据 </h5>
    <form action="/sy3/display" method="post">
        <label> 删除数据学生的学号 </label>
        <input type="text" name="del_sno" value="">
        <input type="submit" value="删除">      
    </form>
</body>
</html>

servlet 负责 jsp 页面与数据库的数据交互

package cn.jdbc.servlet;

import java.io.IOException;
import java.util.ArrayList;
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 cn.jdbc.dao.StudentDao;
import cn.jdbc.domain.student;
import cn.jdbc.test.search_id;

/**
 * Servlet implementation class display
 */
@WebServlet("/display")
public class display extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public display() {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
        // 获取数据库操作的对象
        StudentDao dao = new StudentDao();
        // 获取数组对象
        List<student> list = new ArrayList<student>();
        
        // 获取查询的学号
        String search_sno = request.getParameter("search_no");
        
        // 获取添加的数据
        String add_sno = request.getParameter("add_sno");
        String add_sname = request.getParameter("add_sname");
        String add_sage = request.getParameter("add_sage");
        
        // 获取修改的数据
        String cg_sno = request.getParameter("cg_sno");
        String cg_sname = request.getParameter("cg_sname");
        String cg_sage = request.getParameter("cg_sage");
        
        // 获取删除的学号
        String del_sno = request.getParameter("del_sno");
        
        // 查询数据
        if(search_sno!=null){student student= dao.find(search_sno);    
            list.add(student);
            search_sno="";
        }else{// 显示所有的数据
            list=dao.findAll();}
        // 添加数据
        if(add_sage!=null){student student = new student();
            student.setSno(add_sno);
            student.setSname(add_sname);
            student.setSage(Integer.parseInt(add_sage));
            dao.insert(student);
            list=dao.findAll();
            add_sno="";
            add_sname="";
            add_sage="";
        }
        // 修改数据
        if(cg_sage!=null){student student = new student();
            student.setSno(cg_sno);
            student.setSname(cg_sname);
            student.setSage(Integer.parseInt(cg_sage));
            dao.update(student);
            list=dao.findAll();
            cg_sno="";
            cg_sname="";
            cg_sage="";
        }
        // 删除数据
        if(del_sno!=null){dao.delete(del_sno);
            list=dao.findAll();
            del_sno="";
        }
        // 传递数组到 jsp 页面        
        request.setAttribute("list", list);
        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
        doGet(request, response);
    }

}

C 层

工具类(负责连接数据库)

package cn.jdbc.utils;

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

public class utils {
// 加载驱动,并建立数据库连接
    public static Connection getConnection() throws SQLException,
                ClassNotFoundException {
//        加载驱动
            Class.forName("com.mysql.jdbc.Driver");
//            获取数据库连接
            String url = "jdbc:mysql://localhost:3306/kinjaze";
//            用户名
            String username = "root";
//            密码
                String password = "********";
            Connection conn = DriverManager.getConnection(url, username, 
                    password);
            return conn;
        }
    // 关闭数据库连接,释放资源
    public static void release(ResultSet rs, Statement stmt, Connection conn) {if (rs != null) {
            try {rs.close();
            } catch (SQLException e) {e.printStackTrace();
            }
            rs = null;
        }
        if (stmt != null) {
            try {stmt.close();
            } catch (SQLException e) {e.printStackTrace();
            }
            stmt = null;
        }
        if (conn != null) {
            try {conn.close();
            } catch (SQLException e) {e.printStackTrace();
            }
            conn = null;
        }
        
    }
}

实现数据库的增删改查的操作类

package cn.jdbc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


import cn.jdbc.domain.student;
import cn.jdbc.utils.utils;

/*
 * 完成对数据库的增删改查操作
 */
public class StudentDao {
 // 为学生表添加数据
    public boolean insert(student student) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            // 获得数据的连接
            conn = utils.getConnection();
            // SQL 语句
            String sql="insert into student values(?,?,?)";
            // 得到预编译对象
            stmt=conn.prepareStatement(sql);
            stmt.setString(1, student.getSno());
            stmt.setString(2, student.getSname());
            stmt.setInt(3, student.getSage());
            int num = stmt.executeUpdate();
            if (num > 0) {return true;}
            return false;
        } catch (Exception e) {e.printStackTrace();
        } finally {utils.release(rs, stmt, conn);
        }
        return false;
    }
 // 查询所有数据
    public List < student > findAll() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List < student > list = new ArrayList < student > ();
        try {
            // 获得数据的连接
            conn = utils.getConnection();
            // SQL 语句
            String sql="select * from student";
            // 得到预编译对象
            stmt=conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            // 处理结果集, 遍历 rs 结果集
            while (rs.next()) {student student = new student();
                student.setSno(rs.getString("sno"));
                student.setSname(rs.getString("sname"));
                student.setSage(rs.getInt("sage"));
                list.add(student);
            }
            return list;
        } catch (Exception e) {e.printStackTrace();
        } finally {utils.release(rs, stmt, conn);
        }
        return null;
    }
 // 根据 id 查找指定的 student
    public student find(String id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        student student = new student();
        try {
            // 获得数据的连接
            conn = utils.getConnection();
            //SQL 语句
            String sql = "select * from student where sno=?";
            // 得到预编译对象
            stmt=conn.prepareStatement(sql);
            stmt.setString(1, id);
            rs = stmt.executeQuery();
            // 处理结果集
            while (rs.next()) {student.setSno(rs.getString("sno"));
                student.setSname(rs.getString("sname"));
                student.setSage(rs.getInt("sage"));
                return student;
            }
            return null;
        } catch (Exception e) {e.printStackTrace();
        } finally {utils.release(rs, stmt, conn);
        }
        return null;
    }
 // 删除学生数据
    public boolean delete(String id){
      Connection conn = null;
      PreparedStatement stmt = null;
      ResultSet rs = null;
      try {
          // 获得数据的连接
          conn = utils.getConnection();
          //sql 语句          
          String sql = "delete from student where sno=?";
          // 获取预处理对象        
          stmt= conn.prepareStatement(sql);
          stmt.setString(1, id);
          int num = stmt.executeUpdate();
          if (num > 0) {return true;}
          return false;
      } catch (Exception e) {e.printStackTrace();
      } finally {utils.release(rs, stmt, conn);
      }
      return false;
    }
 // 修改用户
    public boolean update(student student) {
        Connection con = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            // 获得数据的连接
            con = utils.getConnection();
            //sql 语句
            String sql="update student set sname=?,sage=? where sno =?";
            // 得到预编译对象
            stmt=con.prepareStatement(sql);
            stmt.setString(1, student.getSname());
            stmt.setInt(2, student.getSage());
            stmt.setString(3, student.getSno());
            int num = stmt.executeUpdate();
            if (num > 0) {return true;}
            return false;
        } catch (Exception e) {e.printStackTrace();
        } finally {utils.release(rs, stmt, con);
        }
        return false;
    }
}

有其他问题可以私聊作者交流

退出移动版