深擁

导航

连接数据库进行增删改查(基本)下

在上已经写完了关于数据库的连接工具类以及各个层的意义还有查询和删除,现在就来整理关于数据的修改,修改的回显以及增加的过程

1.首先我们来写关于添加的过程

首先是这个页面,在查询的页面上写入增加的超链接

<%@ page language="java"
    pageEncoding="utf-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<title>新闻表</title>
</head>
<body>
    <a href="add.jsp">添加</a>//这里的超链接直接到达了所要添加的这个页面
    <table border="1">
        <tr>
            <td>编号</td>
            <td>标题</td>
            <td>作者</td>
            <td>操作</td>
        </tr>
        <c:forEach items="${list}" var="a" varStatus="status">
        <tr>
            <td>${a.newsId}</td>
            <td>${a.newsTitle}</td>
            <td>${a.newsAuthor}</td>
            <td><a href="DeleteServlet.do?newsId=${a.newsId}">删除</a>
            </td>
        </tr>
        </c:forEach>
    </table>
</body>
</html>

根据数据库中的内容来写一些所要添加的内容显示在页面

<%@ page language="java"
    pageEncoding="utf-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h3>欢迎 ${newsTitle}</h3>
    <form action="AddServlet.do">//form 中的action的这个属性有地址的意义,所以在这里写入处理前台数据的servlet的这个地址,对应的处理添加数据
    <input type="hidden" name="newsId">//因为要获取值,所以这个name属性里的值要与实体类中的字段名保持一致,因为id在mysql数据库里是主键自增的不用填值,所以隐藏起来
    新闻标题:<input type="text" name="newsTitle"><br>
    新闻作者:<textarea cols="4" rows="5" name="newsAuthor"></textarea><br>
    <input type="submit" value="保存">
    </form>
</body>
</html>

接着写dao层的接口

//这个方法是用来添加的,要判断这一条数据是否添加成功,返回的是一个影响行数
  //因为添加的是一条数据,所以传入的参数是一个实体类
    int insertNews(NewsBeng newsBeng);

然后实现类中重写这个方法

@Override
    public int insertNews(NewsBeng newsBeng) {
        // TODO Auto-generated method stub
        Connection conn=null;
        PreparedStatement prestate=null;
        int reslust=0;
        conn=BaseDao.getconn();
        String sql="insert into news values (null,?,?)";
        try {
            prestate=conn.prepareStatement(sql);
            prestate.setString(1, newsBeng.getNewsTitle());//给sql语句中的问号赋值,因为传过来的是一个实体类,所以直接调用从前台传过来的数据给问号赋值
            prestate.setString(2, newsBeng.getNewsAuthor());
            reslust=prestate.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                BaseDao.close(conn, prestate, null);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return reslust;
    }

接着就是servlet层来对数据的一个处理了

package com.bw.ServletPlml;

import java.io.IOException;
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.bw.Beng.NewsBeng;
import com.bw.Dao.plml.NewsDaoPlml;

/**
 * Servlet implementation class AddServlet
 */
@WebServlet("/AddServlet.do")
public class AddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    NewsDaoPlml daoPlml=new NewsDaoPlml();
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String newsTitle = request.getParameter("newsTitle");//这个方法是用来获取前台传过来的值,里面的字段名要与页面的字段名保持一致
        String newsAuthor = request.getParameter("newsAuthor");
        NewsBeng newsBeng=new NewsBeng();//因为要把这所有的数据都传到后台,所以直接new一个实体类以实体类的方式传入后台
        newsBeng.setNewsTitle(newsTitle);//用set方法赋值
        newsBeng.setNewsAuthor(newsAuthor);
        int insertNews = daoPlml.insertNews(newsBeng);//调用dao层的实现类的添加方法
        if (insertNews>0) {
            request.getRequestDispatcher("ShowServlet.do").forward(request, response);//添加完成之后,说明增加数据了,所以要更新数据,重新查询
        }
    }

}

到这里添加就结束了

2.现在是关于修改

还是在查询的页面写入修改的超链接

<%@ page language="java"
    pageEncoding="utf-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<title>新闻表</title>
</head>
<body>
    <a href="add.jsp">添加</a>
    <table border="1">
        <tr>
            <td>编号</td>
            <td>标题</td>
            <td>作者</td>
            <td>操作</td>
        </tr>
        <c:forEach items="${list}" var="a" varStatus="status">
        <tr>
            <td>${a.newsId}</td>
            <td>${a.newsTitle}</td>
            <td>${a.newsAuthor}</td>
            <td><a href="DeleteServlet.do?newsId=${a.newsId}">删除</a>
                |
                <a href="ShowOneServlet.do?newsId=${a.newsId}">修改</a>//这是关于修改的超链接,因为修改和删除只针对一条数据,所以在操作里面写
            </td>
        </tr>
        </c:forEach>
    </table>
</body>
</html>

修改是要看着之前的数据来进行修改,所以这个修改涉及到一个回显

dao层接口里的方法

//修改涉及到一个数据的回显,因为要修改是要参照之前的数据来进行修改,所以这里的方法是根据要修改的这一条数据的id来查找到这要修改的一行数据的内容
  //所以这里返回的是一个实体类,传入的参数也是一个实体类,也可以是id,因为只是根据id查询这一条数据进行回显
    NewsBeng selectnews(NewsBeng newsBeng);

实现类中重写这个方法

@Override
    public NewsBeng selectnews(NewsBeng newsBeng) {
        // TODO Auto-generated method stub
        Connection conn=null;
        PreparedStatement prestate=null;
        NewsBeng newsBeng2=new NewsBeng();//返回的是实体类,所以new一个对应的实体类
        ResultSet res=null;
        conn=BaseDao.getconn();
        String sql="select * from news where newsId=?";
        try {
            prestate=conn.prepareStatement(sql);
            prestate.setInt(1, newsBeng.getNewsId());//给问号赋值
            res=prestate.executeQuery();//获取结果集
            while (res.next()) {
                newsBeng2.setNewsId(res.getInt("newsId"));//把值注入实体类中
                newsBeng2.setNewsTitle(res.getString("newsTitle"));
                newsBeng2.setNewsAuthor(res.getString("newsAuthor"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                BaseDao.close(conn, prestate, res);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }    
        return newsBeng2;//返回这个实体类
    }

servlet层

package com.bw.ServletPlml;

import java.io.IOException;
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.bw.Beng.NewsBeng;
import com.bw.Dao.plml.NewsDaoPlml;

/**
 * Servlet implementation class ShowOneServlet
 */
@WebServlet("/ShowOneServlet.do")
public class ShowOneServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    NewsDaoPlml daoPlml=new NewsDaoPlml();
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String newsId = request.getParameter("newsId");//获取前台传过来的值
        NewsBeng newsBeng=new NewsBeng();
        newsBeng.setNewsId(Integer.parseInt(newsId));//存值
        NewsBeng newsBeng2 = daoPlml.selectnews(newsBeng);//调用方法传值
        if (newsBeng2!=null) {
            request.setAttribute("news", newsBeng2);//把获取到的值传入页面
            request.getRequestDispatcher("update.jsp").forward(request, response);//转发到修改页面
        }
    }

}

修改页面

<%@ page language="java" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h3>欢迎 ${news.newsTitle}</h3>
    <form action="updateServlet.do">
    <input type="hidden" name="newsId" value="${news.newsId}">//value属性就是显示后台传过来的数据的值
    新闻标题:<input type="text" name="newsTitle" value="${news.newsTitle}"><br>
    新闻作者:<textarea cols="4" rows="5" name="newsAuthor">${news.newsAuthor}</textarea><br>
    <input type="submit" value="保存">
    </form>
</body>
</html>

到这里回显就已经搞定了

接下来就是dao层接口写修改的方法

//这是修改的方法,因为要确认修改成功所以返回影响行数,所以是int类型
  //修改是要修改这个数据库里的一行数据,不是单个的数据,所以传入的参数是一个实体类
    int updateNews(NewsBeng newsBeng);

实现类重写这个方法

@Override
    public int updateNews(NewsBeng newsBeng) {
        // TODO Auto-generated method stub
        Connection conn=null;
        PreparedStatement prestate=null;
        int reslust=0;
        conn=BaseDao.getconn();
        String sql="update news set newsTitle=? , newsAuthor=? where newsId=?";
        try {
            prestate=conn.prepareStatement(sql);
            prestate.setString(1, newsBeng.getNewsTitle());//给问号赋值
            prestate.setString(2, newsBeng.getNewsAuthor());
            prestate.setInt(3, newsBeng.getNewsId());
            reslust=prestate.executeUpdate();//返回影响行数
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                BaseDao.close(conn, prestate, null);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return reslust;
    }

servlet层

package com.bw.ServletPlml;

import java.io.IOException;
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.bw.Beng.NewsBeng;
import com.bw.Dao.plml.NewsDaoPlml;

/**
 * Servlet implementation class updateServlet
 */
@WebServlet("/updateServlet.do")
public class updateServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    NewsDaoPlml daoPlml=new NewsDaoPlml();
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String newsId = request.getParameter("newsId");//从前台获取值
        String newsTitle = request.getParameter("newsTitle");
        String newsAuthor = request.getParameter("newsAuthor");
        NewsBeng newsBeng=new NewsBeng();
        newsBeng.setNewsId(Integer.parseInt(newsId));
        newsBeng.setNewsTitle(newsTitle);
        newsBeng.setNewsAuthor(newsAuthor);
        int updateNews = daoPlml.updateNews(newsBeng);//传值
        if (updateNews>0) {
            response.sendRedirect("ShowServlet.do");//这是重定向,跟转发的实现效果类似,这里也是会更新数据
        }
    }

}

 

posted on 2020-03-15 20:59  深擁  阅读(303)  评论(0编辑  收藏  举报