你的位置:首页 > Java教程

[Java教程]对学生表的增删改查操作


      大三暑假在实习,第二周已经结束了,现在可以自己动手写一些比较小的工程。就是写出来调试真的好费人。

简单介绍一下,有一个简单的学生信息表,数据库设计如下:


然后,根据MVC进行分层处理:
    
程序运行结果:
1、查询数据库的结果。

2、点击新增

3、点击编辑,会获取到Id,进行对应的编辑

4、点击删除,直接删除。
package com.mm.bean;public class Student {	int id;//学号	String name;//姓名	int age;//年龄	String classes;//班级		public Student(){}	public int getId() {		return id;	}	public void setId(int id) {		this.id = id;	}	public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public int getAge() {		return age;	}	public void setAge(int age) {		this.age = age;	}	public String getClasses() {		return classes;	}	public void setClasses(String classes) {		this.classes = classes;	}	}

package com.mm.Dao;import java.util.List;import com.mm.bean.Student;public interface IStuDao {	/**	 * 新增一个学生	 * @param stu	 */	public void addstu(Student stu);	/**	 * 修改一个学生	 * @param stu	 */	public void updatestu(Student stu);	/**	 * 通过ID删除一个学生	 * @param id	 */	public void delstu(int id);	/**	 * 找到所有的学生	 * @return 返回一个集合	 */	public List<Student> findall();	/**	 * 通过id找到一个学生	 * @param id	 * @return	 */	public Student findStubyId(int id);}

 

package com.mm.Dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mm.Dao.IStuDao;
import com.mm.bean.Student;
import com.mm.db.JDBCUtils;

public class StuDaoImpl implements IStuDao {

    public void addstu(Student stu) {
        // TODO Auto-generated method stub
        String s1 = "INSERT INTO student (id,name,age,class) VALUES(?,?,?,?)";
        try {
            Connection con = JDBCUtils.getconnection();
            PreparedStatement prep = con.prepareStatement(s1);
            prep.setInt(1, stu.getId());
            prep.setString(2, stu.getName());
            prep.setInt(3, stu.getAge());
            prep.setString(4, stu.getClasses());
            prep.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{

            JDBCUtils.release();
                 }

}
public void updatestu(Student stu) {
          String s1 = "update student set name=?,age=?,class=? where id=?";
          try {
             Connection con = JDBCUtils.getconnection();
             PreparedStatement prep = con.prepareStatement(s1);
             prep.setInt(4, stu.getId()); //第4个问号的值
             prep.setString(1, stu.getName());
             prep.setInt(2, stu.getAge());
             prep.setString(3, stu.getClasses());
             prep.executeUpdate();
             } catch (SQLException e) {
                 e.printStackTrace();
             }finally{

              JDBCUtils.release();
          }

}


public void delstu(int id){
      String s5 = "delete from student where id =?" ;
      Connection con = null;
      try {
         con = JDBCUtils.getconnection();
         PreparedStatement prep = con.prepareStatement(s5);
         prep.setInt(1,id);
         prep.executeUpdate();
        } catch (SQLException e) {
          e.printStackTrace();
        }finally{

           JDBCUtils.release();
                 }
        
        

    }

    public List<Student> findall() {
        
        String s2 = "select * from student";
        Connection con = null;
        List<Student> list = new ArrayList();
        try {
            con = com.mm.db.JDBCUtils.getconnection();
            PreparedStatement ps = con.prepareStatement(s2);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                list.add(toStu(rs));
            }
        } catch (SQLException e) {
        
            e.printStackTrace();
        }finally{

                   JDBCUtils.release();
                 }

         return list;
         }
    
    
//将一行数据封装成一个对象
 private Student toStu(ResultSet rs) throws SQLException {
        Student s = new Student();
        s.setId(rs.getInt("id"));
        s.setName(rs.getString("name"));
        s.setAge(rs.getInt("age"));
        s.setClasses(rs.getString("class"));
        return s;
     }
public Student findStubyId(int id) {
     String s3 = "select * from student where id =" + id;
     Connection con = null;
     PreparedStatement ps = null;
     ResultSet rs = null;
     List<Student> li = new ArrayList();
    try {
    con = com.mm.db.JDBCUtils.getconnection();
    ps = con.prepareStatement(s3);
    rs = ps.executeQuery();
     while (rs.next()) {
         return toStu(rs);
    }
   } catch (SQLException e) { // TODO Auto-generated catch block
       e.printStackTrace();
    }finally{

      JDBCUtils.release();
      }

       return null;
 }
package com.mm.db;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBCUtils {	/**	 * @param args	 * @throws SQLException	 */	public static Connection getconnection() throws SQLException {		try {			Class.forName("com.mysql.jdbc.Driver");			return DriverManager.getConnection(					"jdbc:mysql://localhost:3306/test", "mxning", "mxning");		} catch (ClassNotFoundException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}		return null;	}	public static void release(ResultSet rs,PreparedStatement ps,Connection con){
        
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        if(con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }}

 

package com.mm.sevlet;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.mm.Dao.IStuDao;import com.mm.Dao.impl.StuDaoImpl;import com.mm.bean.Student;public class studentServlet extends HttpServlet {		public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {    IStuDao sd = new StuDaoImpl();    String op = request.getParameter("op");    if(op==null)  op = "list";    if("list".equals(op)){    	//接收 显示所有的请求信息    	List<Student> list = sd.findall();    	request.setAttribute("list", list);    	response.sendRedirect("studentlist.jsp");    	return ;    }else if("add".equals(op)){    	//若是新增,则跳转到新增界面处理    	response.sendRedirect("studentadd.jsp");    	return ;    }else if("edit".equals(op)){    	//取到要编辑的数据,然后 若command=view 则转向view.jsp;否则跳转到编辑页面    	String id = request.getParameter("id");    	//System.out.println(id);    	Student s = sd.findStubyId(Integer.parseInt(id));    	request.setAttribute("stu", s);    	String command = request.getParameter("command");    	if("view".equals(command)){    		request.getRequestDispatcher("studentedit.jsp").forward(request, response);    		//response.sendRedirect("studentedit.jsp");    		return ;    	}else{    		response.sendRedirect("studentview.jsp?id="+id);    		return ;    	}    	    	    }else if("delete".equals(op)){    	//删除数据,然后跳转到列表页面			//1.获取参数值			String id =request.getParameter("id");						//2.调用dao删除指定的数据			sd.delstu(Integer.parseInt(id));						//3.通过response返回到列表页面			response.sendRedirect("studentServlet?op=list");						return ;    }else if("store".equals(op)){			//若是新增,则add;若是编辑,则调用update;然后跳转到列表页面			//1.获取参数值			String id =request.getParameter("id");			String name = request.getParameter("name");			String age = request.getParameter("age");			String classes = request.getParameter("class");			System.out.println(id+name+age);			System.out.println(classes+"sssssssssssssss");			//2.封装成对象			Student obj =new Student();			obj.setName(name);			obj.setAge(Integer.parseInt(age));			obj.setClasses(classes);							if(id==null||"".equals(id)){				//新增				sd.addstu(obj);						//System.out.println("sssssssssssssssssss");							}else{				//编辑				obj.setId(Integer.parseInt(id));				sd.updatestu(obj);							}			response.sendRedirect("studentServlet?op=list");			return ;		}			}		public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {			doGet(request,response);			}}

 

<%@ page language="java"	import="java.util.*,com.mm.Dao.*,com.mm.Dao.impl.*,com.mm.bean.*"	pageEncoding="UTF-8"%><%	String path = request.getContextPath();	String basePath = request.getScheme() + "://"			+ request.getServerName() + ":" + request.getServerPort()			+ path + "/"; request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");	IStuDao is = new StuDaoImpl();	List<Student> list = is.findall();%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>学生列表显示界面</title></head><body>	<table align="center" border="1" cellspacing="0">		<tr>			<td colspan="5"><button					onclick="javascript:document.location.href='studentServlet?op=add';">新增</button>			</td>		</tr>		<tr>			<th>学号</th>			<th>姓名</th>			<th>年龄</th>			<th>班级</th>			<th>操作</th>		</tr>		<%			int i = 1;			for (Student st : list) {		%>		<tr>			<td><%=i%></td>			<td>			<a href="studentview.jsp?op=edit&id=<%=st.getId()%>"><%=st.getName()%></a>			</td>			<td><%=st.getAge()%></td>			<td><%=st.getClasses()%></td>			<td><a href="studentServlet?op=edit&command=view&id=<%=st.getId()%>">编辑</a>  			<a href="studentServlet?op=delete&id=<%=st.getId()%>">删除</a>			</td>		</tr>		<%			i++;			}		%>	</table></body></html>

 

<%@ page language="java" import="java.util.*,com.mm.Dao.*,com.mm.Dao.impl.*,com.mm.bean.*" pageEncoding="UTF-8"%><%	String path = request.getContextPath();	String basePath = request.getScheme() + "://"			+ request.getServerName() + ":" + request.getServerPort()			+ path + "/";				String id = request.getParameter("id");			IStuDao is = new StuDaoImpl();	Student s = is.findStubyId(Integer.parseInt(id));%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>每个学生查看界面</title></head><body>	<h3 align="center">学生查看</h3>		<table align="center" width="60%" border="1" cellspacing="0">	  <tr><td colspan="2"><button onclick="javascript:history.back(-1);">返回</button></td></tr>				<tr>			<td>姓名</td>			<td><%=s.getName()%></td>		</tr>		<tr>			<td>年龄</td>			<td><%=s.getAge()%></td>		</tr>		<tr>			<td>班级</td>			<td><%=s.getClasses() %></td>		</tr>	</table></body></html>

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head>  <base href="<%=basePath%>">    <title>My JSP 'studentadd.jsp' starting page</title> </head>  <body>   <form action="studentServlet?1=1&op=store" method="post">    <table border = "1" cellspacing = "0" align = "center">     <tr>				<th colspan="2" align="left"><button type="submit">提交</button></button>				</th>		</tr>				<tr><td>姓名</td><td><input type = "text" name = "name" /></td></tr>		<tr><td>年龄</td><td><input type = "text" name = "age" /></td></tr>		<tr><td>班级</td><td><input type = "text" name = "class" /></td></tr>       </table>    </form>     </body></html>

 

<%@ page language="java" import="java.util.*,com.mm.bean.*,com.mm.sevlet.*"	pageEncoding="UTF-8"%><%	String path = request.getContextPath();	String basePath = request.getScheme() + "://"			+ request.getServerName() + ":" + request.getServerPort()			+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>修改学生界面</title></head><body>	<%		Student s = (Student) request.getAttribute("stu");	%>	<form action="studentServlet?op=store" method = "post">		<input type="hidden" name="id" value="<%=s.getId()%>" />		<table border="1" align="center" cellspacing="0">			<tr>				<td colspan="2"><button type="submit">提交</button>  									<button type="button" onclick="javascript:history.back(-1);">返回</button>				</td>			</tr>						<tr>				<td>姓名</td>				<td><input type="text" name="name" value="<%=s.getName()%>" />				</td>			</tr>			<tr>				<td>年龄</td>				<td><input type="text" name="age" value="<%=s.getAge()%>" />				</td>			</tr>			<tr>				<td>班级</td>				<td><input type="text" name="class" value="<%=s.getClasses()%>" />				</td>			</tr>		</table>	</form></body></html>