使用java servlet删除表行

时间:2016-05-27 21:02:07

标签: java jsp servlets

我正在尝试使用mysql和java servlet从表中删除一行。

DAO代码

public class StudyDAO {
    private String driver="com.mysql.jdbc.Driver";
    private String url="jdbc:mysql://localhost:3306/mydb";
    private String dbuser="root";
    private String dbpassword="root123";
    private String delstuSQL="delete from stu where email=?";
    private Connection con;
    private PreparedStatement pstmtdelstu;

    public StudyDAO()throws ClassNotFoundException,SQLException{
        Class.forName(driver);
        con=DriverManager.getConnection(url,dbuser,dbpassword);
    pstmtdelstu=con.prepareStatement(delstuSQL);
    }
    public void delstu(Student s) throws SQLException{
        pstmtdelstu.setString(1, s.getEmail());
        pstmtdelstu.executeUpdate();
    }       
}

Servlet代码

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // TODO Auto-generated method stub
    try
    {
        String email=req.getParameter("email");
        StudyDAO dao=new StudyDAO();                                                        
        }
    catch(ClassNotFoundException e){
            e.printStackTrace();
            res.sendError(9999,"Error in classloading");
        }
    catch(SQLException e){
            e.printStackTrace();
            res.sendError(9998,"Error in sql:"+e.getMessage()+"Error code:"+e.getErrorCode()+e.getSQLState());
        }
    catch(Exception e){
            res.sendError(8000,"Unknown Error"+e.getMessage());
        }
    }

JSP代码

<body>
    <div id="header">
        <h1>Students Account's Details</h1>
    </div>
    <% Collection<Student> list=(Collection<Student>)session.getAttribute("LIST"); %>
    <%if(list!=null) {%>
         <table border=1>
        <th><th>First name</th><th>Last name</th><th>Email</th>.  <th>Year</th><th>Department</th><th>Mobile</th></tr>
<%for(Student s:list){ %>
        <tr><td><%=s.getFname() %></td><td><%=s.getLname() %></td><td><%=s.getEmail() %></td><td><%=s.getYear() %></td><td><%=s.getDept()%></td>
        <td><%=s.getMobile() %></td><td><a href="DeleteStu?email=<%=s.getEmail() %> " >Delete</a></td></tr>

    <% } %>
    </table>
        <% } else{%>
        <h3>No records found.</h3>
        <% }%>
    </body>
</html>

不知道我该怎么做才能删除一行。我已经尝试过上面的DAO,DeleteServlet,jsp代码。请查看和帮助。

1 个答案:

答案 0 :(得分:0)

在实例化StudyDAO后,您没有调用dao.delstu(student)。由于delstu获得了整个学生,即使它只需要电子邮件,您也可以创建一个虚拟学生并设置其电子邮件:

String email=req.getParameter("email");
StudyDAO dao=new StudyDAO();
Student dummy = new Student(email); // or new Student(); dummy.setEmail(email);
dao.delstu(dummy);

作为一种更清洁的替代方案,您可能希望修改delstu方法以直接通过以下方式删除要删除的电子邮件:

public void deleteStudentByEmail(String email) throws SQLException{
    pstmtdelstu.setString(1, email);
    pstmtdelstu.executeUpdate();
}