MVC模式實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪改查

什么是MVC模式

MVC模式中M代表模型、V代表視圖、C代表控制器。
Model(模型)表示應(yīng)用程序核心(比如數(shù)據(jù)庫(kù)記錄列表)。
View(視圖)顯示數(shù)據(jù)(數(shù)據(jù)庫(kù)記錄)。
Controller(控制器)處理輸入(寫(xiě)入數(shù)據(jù)庫(kù)記錄)。

數(shù)據(jù)庫(kù)設(shè)計(jì)

表名:student、使用的為mysql數(shù)據(jù)庫(kù)


image.png

M層

package cn.jdbc.domain;

public class student {
//學(xué)號(hào)
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頁(yè)面

<%@ 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>學(xué)生數(shù)據(jù)</title>
</head>
<body>
    <table border="1" border="1" cellpadding="0" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>學(xué)號(hào)</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>查詢(xún)的學(xué)號(hào)</label>
        <input type="text" name="search_no" value="">
        <input type="submit" value="查詢(xún)">
        <a href="http://localhost:9999/sy3/display">返回</a><br>      
    </form>
    <h5>添加數(shù)據(jù)</h5>
    <form action="/sy3/display" method="post">
        <label>學(xué)號(hào)</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>修改數(shù)據(jù)</h5>
    <form action="/sy3/display" method="post">
        <label>學(xué)號(hào)</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>刪除數(shù)據(jù)</h5>
    <form action="/sy3/display" method="post">
        <label>刪除數(shù)據(jù)學(xué)生的學(xué)號(hào)</label>
        <input type="text" name="del_sno" value="">
        <input type="submit" value="刪除">      
    </form>
</body>
</html>
image.png

servlet負(fù)責(zé)jsp頁(yè)面與數(shù)據(jù)庫(kù)的數(shù)據(jù)交互

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
        //獲取數(shù)據(jù)庫(kù)操作的對(duì)象
        StudentDao dao = new StudentDao();
        //獲取數(shù)組對(duì)象
        List<student> list = new ArrayList<student>();
        
        //獲取查詢(xún)的學(xué)號(hào)
        String search_sno = request.getParameter("search_no");
        
        //獲取添加的數(shù)據(jù)
        String add_sno = request.getParameter("add_sno");
        String add_sname = request.getParameter("add_sname");
        String add_sage = request.getParameter("add_sage");
        
        //獲取修改的數(shù)據(jù)
        String cg_sno = request.getParameter("cg_sno");
        String cg_sname = request.getParameter("cg_sname");
        String cg_sage = request.getParameter("cg_sage");
        
        //獲取刪除的學(xué)號(hào)
        String del_sno = request.getParameter("del_sno");
        
        //查詢(xún)數(shù)據(jù)
        if(search_sno!=null){
            student student= dao.find(search_sno);  
            list.add(student);
            search_sno="";
        }else{//顯示所有的數(shù)據(jù)
            list=dao.findAll();
        }
        //添加數(shù)據(jù)
        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="";
        }
        //修改數(shù)據(jù)
        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="";
        }
        //刪除數(shù)據(jù)
        if(del_sno!=null){
            dao.delete(del_sno);
            list=dao.findAll();
            del_sno="";
        }
        //傳遞數(shù)組到j(luò)sp頁(yè)面        
        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層

工具類(lèi)(負(fù)責(zé)連接數(shù)據(jù)庫(kù))

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 {
// 加載驅(qū)動(dòng),并建立數(shù)據(jù)庫(kù)連接
    public static Connection getConnection() throws SQLException,
                ClassNotFoundException {
//      加載驅(qū)動(dòng)
            Class.forName("com.mysql.jdbc.Driver");
//          獲取數(shù)據(jù)庫(kù)連接
            String url = "jdbc:mysql://localhost:3306/kinjaze";
//          用戶名
            String username = "root";
//          密碼
                String password = "********";
            Connection conn = DriverManager.getConnection(url, username, 
                    password);
            return conn;
        }
    // 關(guān)閉數(shù)據(jù)庫(kù)連接,釋放資源
    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;
        }
        
    }
}

實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪改查的操作類(lèi)

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;

/*
 * 完成對(duì)數(shù)據(jù)庫(kù)的增刪改查操作
 */
public class StudentDao {
 //為學(xué)生表添加數(shù)據(jù)
    public boolean insert(student student) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            // 獲得數(shù)據(jù)的連接
            conn = utils.getConnection();
            // SQL語(yǔ)句
            String sql="insert into student values(?,?,?)";
            //得到預(yù)編譯對(duì)象
            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;
    }
 //查詢(xún)所有數(shù)據(jù)
    public List < student > findAll() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List < student > list = new ArrayList < student > ();
        try {
            // 獲得數(shù)據(jù)的連接
            conn = utils.getConnection();
            // SQL語(yǔ)句
            String sql="select * from student";
            //得到預(yù)編譯對(duì)象
            stmt=conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            // 處理結(jié)果集,遍歷rs結(jié)果集
            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;
    }
 // 根據(jù)id查找指定的student
    public student find(String id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        student student = new student();
        try {
            // 獲得數(shù)據(jù)的連接
            conn = utils.getConnection();
            //SQL語(yǔ)句
            String sql = "select * from student where sno=?";
            //得到預(yù)編譯對(duì)象
            stmt=conn.prepareStatement(sql);
            stmt.setString(1, id);
            rs = stmt.executeQuery();
            // 處理結(jié)果集
            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;
    }
 //刪除學(xué)生數(shù)據(jù)
    public boolean delete(String id){
      Connection conn = null;
      PreparedStatement stmt = null;
      ResultSet rs = null;
      try {
          // 獲得數(shù)據(jù)的連接
          conn = utils.getConnection();
          //sql語(yǔ)句          
          String sql = "delete from student where sno=?";
          //獲取預(yù)處理對(duì)象        
          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 {
            //獲得數(shù)據(jù)的連接
            con = utils.getConnection();
            //sql語(yǔ)句
            String sql="update student set sname=?,sage=? where sno =?";
            //得到預(yù)編譯對(duì)象
            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;
    }
}

有相關(guān)問(wèn)題歡迎與作者私聊探討交流

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容