增删改查(简单版&连接数据库)
Posted hhjing
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了增删改查(简单版&连接数据库)相关的知识,希望对你有一定的参考价值。
项目总述:这个增删改查我以,选课名称,选课教室,选课教师基本信息,作为主要的信息来源。主要对这些信息最基本的增删改查
详细的分析与说明:
1.首先在src文件里定义四个包,com.bean(定义类),com.dao(对数据进行处理,书写增删改查的函数),com.db(用于连接数据库),com.servlet(用于接受jsp中传输的值,并对其进行判断处理)
相关代码展示:
Bean.java:
package com.bean; public class Bean { private String name; private String teacher; private String classroom; public Bean() { super(); } public Bean(String name, String teacher, String classroom) { super(); this.name = name; this.teacher = teacher; this.classroom = classroom; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTeacher() { return teacher; } public void setTeacher(String teacher) { this.teacher = teacher; } public String getClassroom() { return classroom; } public void setClassroom(String classroom) { this.classroom = classroom; } @Override public String toString() { return "Bean [name=" + name + ", teacher=" + teacher + ", classroom=" + classroom + "]"; } }
Dao.java:
package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.sql.ResultSet; import java.sql.SQLException; import com.db.DB; import com.servlet.selectNameServlet; import com.servlet.updateServlet; import com.db.DB; import com.bean.Bean; public class Dao { //增加 @SuppressWarnings("static-access") public boolean add(Bean bean) { String tablename = "test";//表名 DB db=new DB(); Connection con = db.getCon(); try { String sql="insert into "+tablename+"(name,teacher,classroom) values (‘"+bean.getName()+"‘,‘"+bean.getTeacher()+"‘,‘"+bean.getClassroom()+"‘)"; Statement stm = con.createStatement(); System.out.println(sql); stm.execute(sql); db.close(stm, con); }catch(Exception e) { e.printStackTrace(); System.out.println("add false"); return false; } System.out.println("add true"); return true; } //根据名称进行查询 @SuppressWarnings("static-access") public static Bean selectName(String name) { String tablename = "test"; System.out.println("select bean where name = "+name); Bean bean=null; DB db=new DB(); Connection con = db.getCon(); try { Statement stm = con.createStatement(); //閿熸枻鎷烽敓鏂ゆ嫹value1=name閿熸枻鎷烽敓鏂ゆ嫹閿熸嵎锝忔嫹閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷烽敓琛楄鎷烽敓鏂ゆ嫹閿熸枻鎷? ResultSet rs = stm.executeQuery("select * from "+tablename+" where name=‘" + name + "‘"); /* * 閿熸枻鎷烽敓鏂ゆ嫹value1=name閿熸枻鎷烽敓鏂ゆ嫹閿熸嵎锝忔嫹閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷烽敓鏂ゆ嫹value3閿熸枻鎷烽敓琛楄鎷烽敓鏂ゆ嫹閿熸枻鎷? * ResultSet rs =stm.executeQuery("select value3 from "+tablename+" where value2="+i); */ if(rs.next()) { bean = new Bean(); System.out.println("select the bean from mysql"); bean.setName(rs.getString("name")); bean.setTeacher(rs.getString("teacher")); bean.setClassroom(rs.getString("classroom")); //bean.setValue2(Integer.parseInt(rs.getString("teacher"))); //bean.setValue3(Boolean.parseBoolean(rs.getString("address"))); System.out.println("name of the bean is "+rs.getString("name")); } db.close(rs,stm, con); }catch(Exception e) { e.printStackTrace(); } return bean; } //删除 @SuppressWarnings("static-access") public static boolean delete(String name) { //String tablename ="test"; DB db=new DB(); Connection con = db.getCon(); //Connection con=null; PreparedStatement stm=null; try { con=DB.getCon(); String sql="delete from test where name=‘"+name+"‘"; //String sql="delete from test where name=‘"+bean.getName()+"‘"; System.out.println(sql); stm=con.prepareStatement(sql); stm.executeUpdate(); return true; } catch(SQLException e) { e.printStackTrace(); } finally { db.close(stm, con); } return false; } //修改 @SuppressWarnings("static-access") public boolean update(Bean bean) { Connection con=null; PreparedStatement stm=null; String tablename="test"; DB db=new DB(); try { con=DB.getCon(); String sql="update "+tablename+" set teacher=?,classroom=? where name=?"; //String sql="update "+tablename+"set teacher=?,classroom=? where name=?"; stm=con.prepareStatement(sql); stm.setString(3,bean.getName()); stm.setString(1, bean.getTeacher()); stm.setString(2,bean.getClassroom()); stm.executeUpdate(); } catch(SQLException e) { e.printStackTrace(); return false; } finally { db.close(stm, con); return true; } } //根据名字进行查找 public boolean findName(String name){ boolean flag=false; Connection con=null; PreparedStatement psts=null; ResultSet rs=null; String tablename="test"; DB db=new DB(); try { con=db.getCon(); String sql="select * from"+tablename+" where name=?"; psts=con.prepareStatement(sql); psts.setString(1, name); rs=psts.executeQuery(); while(rs.next()){ flag=true; } } catch (SQLException e) { e.printStackTrace(); } return flag; } // @SuppressWarnings("static-access") public ArrayList<Bean> selectList(){ Connection con=null; PreparedStatement stm=null; ResultSet rs=null; ArrayList<Bean> listbean=new ArrayList<Bean>(); String tablename="test"; DB db=new DB(); try { con=db.getCon(); String sql="select * from "+tablename; stm=con.prepareStatement(sql); rs=stm.executeQuery(); while(rs.next()){ String name=rs.getString("name"); String teacher=rs.getString("teacher"); String classroom=rs.getString("classroom"); Bean bean=new Bean(name,teacher,classroom); listbean.add(bean); } } catch(SQLException e) { e.printStackTrace(); } finally { db.close(stm, con); } return listbean; } } // // public Bean login(String name,String password) { // String tablename = null; // DB db=new DB(); // Connection con = db.getCon(); // Bean bean = null; // try { // Statement stm = con.createStatement(); // ResultSet rs = stm.executeQuery("select * from "+tablename+" where value1=‘" + name + "‘"); // if(rs.next()) { // if (rs.getString("password").equals(password)) { // // } // } // }catch(Exception e) { // // } // }
DB.java:
package com.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.Test; public class DB { private static String mysqlname = "database";//数据库名 private static Connection con; private static Statement stm; private static ResultSet rs; private static String coursename = "com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://127.0.0.1:3306/"+mysqlname+"?useUnicode=true&characterEncoding=GB18030&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true"; public static Connection getCon() { try { Class.forName(coursename); System.out.println("注册驱动成功"); }catch(ClassNotFoundException e) { e.printStackTrace(); } try { con = DriverManager.getConnection(url,"root","20000604"); System.out.println("建立连接成功"); }catch(Exception e){ e.printStackTrace(); con = null; } return con; } public static void close(Statement stm,Connection connection) { if(stm!=null) { try { stm.close(); }catch(SQLException e) { e.printStackTrace(); } } if(connection!=null) { try { connection.close(); }catch(SQLException e) { e.printStackTrace(); } } } //关闭 public static void close(ResultSet rs,Statement stm,Connection connection) { if(rs!=null) { try { rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(stm!=null) { try { stm.close(); }catch(SQLException e) { e.printStackTrace(); } } if(connection!=null) { try { connection.close(); }catch(SQLException e) { e.printStackTrace(); } } } public static void main(String[] args) { getCon(); } }
addServlet.java:
package com.servlet; 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.bean.Bean; import com.dao.Dao; /** * Servlet implementation class addServlet */ @WebServlet("/addServlet") public class addServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); Bean bean = new Bean(); bean.setName(request.getParameter("name")); bean.setTeacher(request.getParameter("teacher")); bean.setClassroom(request.getParameter("classroom")); Dao dao = new Dao(); if(dao.add(bean)) { request.setAttribute("message", "添加成功"); request.getRequestDispatcher("add.jsp").forward(request,response); //response.sendRedirect("index.jsp"); } else { request.setAttribute("message","添加失败"); request.getRequestDispatcher("add.jsp").forward(request,response); //response.sendRedirect("add.jsp"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
deleteServlet.java:
package com.servlet; import java.io.IOException; import java.io.PrintWriter; 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.bean.Bean; import com.dao.Dao; /** * Servlet implementation class deleteServlet */ @WebServlet("/deleteServlet") public class deleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Dao dao=new Dao(); if(dao.delete(request.getParameter("delete"))) { //request.setAttribute("message鈥濓紝"鍒犻櫎鎴愬姛"); //response.sendRedirect("index.jsp"); request.setAttribute("message", "删除成功"); request.getRequestDispatcher("delete.jsp").forward(request,response); //response.sendRedirect("index.jsp"); } else { request.setAttribute("message", "删除失败"); request.getRequestDispatcher("delete.jsp").forward(request,response); //response.sendRedirect("index.jsp");//response.sendRedirect("delete.jsp"); } } /** * @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); } }
selectNameServlet.java:
package com.servlet; 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.bean.Bean; import com.dao.Dao; /** * Servlet implementation class selectNameServlet */ @WebServlet("/selectNameServlet") public class selectNameServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Bean bean=new Bean(); bean.setName(request.getParameter("selectname")); Dao dao=new Dao(); bean = dao.selectName(bean.getName()); if(bean!=null) { request.setAttribute("Bean",bean); request.getRequestDispatcher("select_show.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); } }
showAllServlet.java:
package com.servlet; 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.bean.Bean; import com.dao.Dao; /** * Servlet implementation class selectNameServlet */ @WebServlet("/selectNameServlet") public class selectNameServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Bean bean=new Bean(); bean.setName(request.getParameter("selectname")); Dao dao=new Dao(); bean = dao.selectName(bean.getName()); if(bean!=null) { request.setAttribute("Bean",bean); request.getRequestDispatcher("select_show.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); } }
updatenewServlet.java:
package com.servlet; 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.bean.Bean; import com.dao.Dao; /** * Servlet implementation class updatenewServlet */ @WebServlet("/updatenewServlet") public class updatenewServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); request.setCharacterEncoding("UTF-8"); Bean beannew=new Bean(); Dao dao=new Dao(); beannew.setName(request.getParameter("updatename")); beannew.setTeacher(request.getParameter("updateteacher")); beannew.setClassroom(request.getParameter("updateclassroom")); //System.out.println("接受成功"); //System.out.println(request.getParameter("updatename")); //bean.setValue2(Integer.parseInt(request.getParameter("value2"))); //bean.setValue3(Boolean.parseBoolean(request.getParameter("value3"))); if(dao.update(beannew)) { response.sendRedirect("index.jsp"); } else { response.sendRedirect("update_show.jsp"); } } /** * @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); } }
updateServlet:
package com.servlet; import java.io.IOException; import java.io.PrintWriter; 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.bean.Bean; import com.dao.Dao; /** * Servlet implementation class updateServlet */ @WebServlet("/updateServlet") public class updateServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Bean bean=new Bean(); Bean beanform=new Bean(); Dao dao=new Dao(); bean = dao.selectName(request.getParameter("selectname")); System.out.println(request.getParameter("selectname")); if(bean!=null) { request.setAttribute("Bean",bean); request.getRequestDispatcher("update_show.jsp").forward(request,response); } // else if(bean==null) { // request.setAttribute("Bean",bean); // request.getRequestDispatcher("delete.jsp").forward(request,response); // return ; // } // beanform.setName(request.getParameter("updatename")); // beanform.setTeacher(request.getParameter("updateteacher")); // beanform.setClassroom(request.getParameter("updateclassroom")); // //bean.setValue2(Integer.parseInt(request.getParameter("value2"))); // //bean.setValue3(Boolean.parseBoolean(request.getParameter("value3"))); // if(dao.update(beanform)) { // //request.setAttribute("message", "娣诲姞鎴愬姛"); // response.sendRedirect("index.jsp"); // } // else { // //request.setAttribute("message","娣诲姞澶辫触"); // response.sendRedirect("update.jsp"); // } } }
2.然后继续完成前端页面:
代码展示:
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>首界面</title> </head> <body> <div> <h1 align="center" color="blue"> 增删改查的主页面</h1> <hr/> <a href="add.jsp"><h2 align="center">添加课程信息</a></h2> <a href="delete.jsp"><h2 align="center">删除课程信息</a></h2> <a href="update.jsp"><h2 align="center">修改课程信息</h2></a> <a href="select.jsp"><h2 align="center">查询课程信息</h2></a> <a href="showAllServlet" ><h2 align="center">浏览课程全部信息</h2></a> </div> </body> </html>
add.jsp:
<%@page import="java.util.jar.Attributes.Name"%> <%@page import="com.servlet.addServlet" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>添加课程</title> </head> <body> <% String mess=(String)request.getAttribute("message"); if(mess!=null&&!"".equals(mess)){ %> <script type="text/javascript"> alert("<%=mess%>"); </script> <% } %> <div align="center"> <form action="addServlet" method="post"> <a href="index.jsp"><h2>返回主界面</h2></a> <div > <table> <tr> <td>添加课程:</td> <td><input type="text" id="name" name="name"></td> </tr> <tr> <td>添加教师:</td> <td><input type="text" id="teacher" name="teacher"></td> </tr> <tr> <td>添加地点:</td> <td><input type="text" id="classroom" name="classroom"></td> </tr> <tr> <td><input align="center" type="submit" value="添加"></td> </tr> </table> </div> </form> </div> </body> </html>
delete.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>删除课程</title> </head> <body> <% String mess=(String)request.getAttribute("message"); if(mess!=null&&!"".equals(mess)){ %> <script type="text/javascript"> alert("<%=mess%>"); </script> <% } %> <form align="center" action="deleteServlet" method="post"> <div> <h4><a href="index.jsp">返回主界面</a></h4> <table> <tr> <td>根据名字进行删除:</td> </tr> <tr> <td>请输入需要删除课程的名字:</td> <td><input type="text" name="delete" value=""></td> </tr> <tr> <input type="submit" value="确定" id=""> </tr> </table> </div> </form> </body> </html>
select.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>查询课程信息</title> </head> <body> <% String mess=(String)request.getAttribute("message"); if(mess!=null&&!"".equals(mess)){ %> <script type="text/javascript"> alert("<%=mess%>"); </script> <% } %> <h2 align="cneter">课程查询</h2> <hr/> <form align="center" action="selectNameServlet" method="post"> <div> <table> <tr> <td>根据名字进行查询:</td> </tr> <tr> <td>请输入需要查询课程的名字:</td> <td><input type="text" name="selectname" value=""></td> </tr> <tr> <input type="submit" value="确定" id=""> </tr> <a href="index.jsp">返回主页面</a> </table> </div> </form> </body> </html>
select_show.jsp:
<%@page import="com.bean.Bean"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>查询显示</title> </head> <body> <% Bean b2=(Bean)request.getAttribute("Bean"); %> <form action="selectServlet" method="post"> <table> <tr> <td>显示课程名字:</td> <td><input type="text" name="" value="<%=b2.getName()%>"></td> </tr> <tr> <td>显示课程教师:</td> <td><input type="text" name="" value="<%=b2.getTeacher()%>"></td> </tr> <tr> <td>显示课程地点:</td> <td><input type="text" naem="" value="<%= b2.getClassroom()%>"></td> </tr> </table> <a href="index.jsp">返回主界面</a> </form> </body> </html>
update.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>显示所要修改的课程</title> </head> <body> <form action="updateServlet" method="post"> <tr> <td>请输入所要修改的课程的名字:</td> <td><input type="text" name="selectname" value=""></td> </tr> <tr> <input type="submit" value="确定" id=""> </tr> </form> </body> </html>
update_show.jsp:
<%@page import="com.bean.Bean"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>修改课程信息</title> </head> <% Bean b2=(Bean)request.getAttribute("Bean"); %> <body> <form action="updatenewServlet" method="post"> <table> <h4>修改前的课程信息:</h4> <tr> <td>课程名字:</td> <td><input type="text" name="" value="<%=b2.getName()%>"></td> </tr> <tr> <td>课程教师:</td> <td><input type="text" name="" value="<%=b2.getTeacher()%>"></td> </tr> <tr> <td>课程地点:</td> <td><input type="text" name="" value="<%= b2.getClassroom()%>"></td> </tr> </table> <hr/> <h4>修改后的课程信息</h4> <table> <tr> <td>请输入所要修改的课程名称:</td> <td><input type="text" name="updatename" value=""></td> </tr> <tr> <td>请输入修改后的课程教师:</td> <td><input type="text" name="updateteacher" value=""></td> <tr> <td>请输入修改后的上课地点:</td> <td><input type="text" name="updateclassroom" value=""></td> </tr> <tr> <input type="submit" value="确定" id=""> </tr> </table> <a href="index.jsp">返回主页面</a> </form> </body> </html>
showall.jsp:
<%@page import="com.dao.Dao"%> <%@page import="com.bean.Bean"%> <%@page import="java.util.ArrayList"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%-- <%@ page isELIgnored="false" %> --%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>显示全部信息</title> </head> <body> <!-- <form action="showAllServlet" method="post"> --> <tr><h3>所有课程信息:</h3></tr> <hr/> <table> <tr> <td>课程名称</td> <td>课程教师</td> <td>课程地点</td> </tr> <c:forEach items="${listbean}" var="item"> <tr> <td>${item.name}</td> <td>${item.teacher}</td> <td>${item.classroom}</td> </tr> </c:forEach> </table> <a href="index.jsp">返回主界面</a> </form> </html>
所遇到的问题:
1.在update_show.jsp的显示页面中,他的组成部分为两部分,一是显示需要修改之前的全部信息,二是输入修改之后的信息。界面如下所示
所遇问题是保存不成功修改后的信息,原因:在updatenewServlet.java没有接收到update_show.jsp所要传输的信息
2.在显示全部信息的时,不能全部的显示:
界面如下:
理应如下:
原因:自己对于forEach语句的不熟练照成,需要多多学习,多多练习。
以上是关于增删改查(简单版&连接数据库)的主要内容,如果未能解决你的问题,请参考以下文章