使用JDBC連接MySQL數據庫操作增刪改查


更多精彩內容歡迎訪問我的個人博客皮皮家園:http://www.zhsh666.xyz或者http😕/www.zh66.club期待您的光臨哦!我是皮皮豬,感謝各位光臨,能為您排憂解難小站深感榮幸!祝您生活愉快!

@

1.首先這個Myeclipse的包名以及一些實現的類(這樣子寫是我的習慣)

[外鏈圖片轉存失敗(img-33fh5Nqc-1567778008409)(https://cdn.jsdelivr.net/gh/Zevs6/blogimg/img/201803292248062741)]

2.接下來我們創建數據庫(MySQL)

3.在數據庫里面添加數據

[外鏈圖片轉存失敗(img-gaEzca3V-1567778008410)(https://cdn.jsdelivr.net/gh/Zevs6/blogimg/img/201803292305071371)]

4.首先是BaseDao,這個是重中之重,注意那個數據庫的名字,強調所在的包名

package dao;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class BaseDao {
 
	/***
	 * 
	 * @author 數據庫連接類
	 *
	 */
		private String driver ="com.mysql.jdbc.Driver";
		private String url="jdbc:mysql://localhost:3306/表名";        ---------自己寫數據庫表名,只要數據庫的表名跟這里的一樣就行
		private String name="數據庫名稱";      ----------你自己數據庫的名稱
		private String pwd="密碼";        -----------你自己數據庫的密碼
	      Connection conn=null;
	      /***
	       * 
	       * @return 打開連接
	       */
	    /*  public Connection getconn(){
	  		Connection conn=null;
	  		Context ctx;
	  		try {
	  			ctx = new InitialContext();
	  			DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/news");	
	  	    	conn=ds.getConnection();
	  		}catch (Exception e) {
	  			e.printStackTrace();
	  		}
	  		return conn;
	  	}     */
		protected  Connection getconn(){
			conn=null;	
			try {
				Class.forName(driver);
				conn=DriverManager.getConnection(url,name,pwd);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
			return conn;
		}
		
		/****
		 * 
		 * @param 關閉數據庫連接
		 */
		protected void closeAll(Connection conn ,PreparedStatement ps,ResultSet rs){		
			if(rs!=null)
				try {
					if(rs!=null)
					rs.close();
					if(ps!=null)
					ps.close();
					if(conn!=null)
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
		}
		/***
		 * 
		 * @param 增刪改方法
		 * @param 接受 參數為 SQL語句 和 對象數組
		 * @return 返回受影響行數
		 */
		public int executeUpdate(String sql ,Object []ob){
			conn=getconn();
			PreparedStatement ps=null;
			try {
				ps=prepareStatement(conn,sql,ob);
				int i=ps.executeUpdate();
				return i;	
			} catch (SQLException e) {
				// TODO Auto-generated catch block
			    //	e.printStackTrace();
				return 0;
			}finally{			
				closeAll(conn, ps, null);
			}
		
		}	
		/***
		 * 查詢方法
		 */
		protected PreparedStatement prepareStatement(Connection conn,String sql,Object []ob){		
			PreparedStatement ps=null;
					try {
						int index=1;
						ps = conn.prepareStatement(sql);
							if(ps!=null&&ob!=null){
								for (int i = 0; i < ob.length; i++) {			
										ps.setObject(index, ob[i]);	
										index++; 
								}
							}
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
			 return ps;
		}
	
}

5.這個是實體類,我相信大家都會寫,注意所在的包名

package entity;
 
public class Booking {
	private int id;
	private int categoryId;
	private String title;
	private String summary;
	private String uploaduser;
	private String createdate;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getCategoryId() {
		return categoryId;
	}
	public void setCategoryId(int categoryId) {
		this.categoryId = categoryId;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getSummary() {
		return summary;
	}
	public void setSummary(String summary) {
		this.summary = summary;
	}
	public String getUploaduser() {
		return uploaduser;
	}
	public void setUploaduser(String uploaduser) {
		this.uploaduser = uploaduser;
	}
	public String getCreatedate() {
		return createdate;
	}
	public void setCreatedate(String createdate) {
		this.createdate = createdate;
	}
	
	
}

6.接下來我們寫BookingDao

package dao;
 
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 entity.Booking;
 
public class BookingDao extends BaseDao{
	
	public List<Booking> search(String sql,Object...params){
		List<Booking> list =new ArrayList<Booking>();
		Connection conn=this.getconn();
		PreparedStatement pst=null;
		ResultSet rs=null;
		try {
			pst=this.prepareStatement(conn, sql, params);
			rs=pst.executeQuery();
			while(rs.next()){
				Booking wor=new Booking();
				wor.setId(rs.getInt(1));
				wor.setCategoryId(rs.getInt(2));
				wor.setTitle(rs.getString(3));
				wor.setSummary(rs.getString(4));
				wor.setUploaduser(rs.getString(5));
				wor.setCreatedate(rs.getString(6));
				list.add(wor);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(conn, pst, rs);
		}
		return list;
	}
	
	//查詢表
	public List<Booking> findAll(){
		String sql="SELECT * FROM `Book`";
		return search(sql);
	}
	
	//添加方法
	public int insert(Booking t){
		String str="INSERT INTO `book`(categoryId,title,summary,uploaduser,createdate) VALUE(?,?,?,?,?)";
		return executeUpdate(str, new Object[]{t.getCategoryId(),t.getTitle(),t.getSummary(),t.getUploaduser(),t.getCreatedate()});
	}
	
	//修改方法
	public int update(Booking r){
		String sql="UPDATE `book` SET `categoryId`=?,`title`=?,`summary`=?,`uploaduser`=?,`createdate`=? WHERE id=?";
		return executeUpdate(sql, new Object[]{r.getCategoryId(),r.getTitle(),r.getSummary(),r.getUploaduser(),r.getCreatedate(),r.getId()});
	}
	
	//刪除方法
	public int delete(Booking e){
		String sql="DELETE FROM `book` WHERE id=?";
		return executeUpdate(sql, new Object[]{e.getId()});
	}
	
	
}

7.下面我們寫Servlet

1.查詢的Servlet

package servlet;
 
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 dao.BookingDao;
import entity.Booking;
 
public class selectServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public selectServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		String opr=request.getParameter("opr");
		
	
		if(opr==null||opr.equals("list")){
			//刷新
			BookingDao goodsDao=new BookingDao();
			List<Booking> list=goodsDao.findAll();
			request.getSession().setAttribute("list", list);
			response.sendRedirect("index.jsp");
		}
		
		
		
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}

2.添加的Servlet

package servlet;
 
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 dao.BookingDao;
import entity.Booking;
 
public class insertServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public insertServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		BookingDao rms=new BookingDao(); 
		  int categoryId=Integer.parseInt(request.getParameter("categoryId"));
		  String title=request.getParameter("title");
		  String summary=request.getParameter("summary");
		  String uploaduser=request.getParameter("uploaduser");
		  String createdate=request.getParameter("createdate");
		  Booking rm=new Booking();
			  rm.setCategoryId(categoryId);
			  rm.setTitle(title);
			  rm.setSummary(summary);
			  rm.setUploaduser(uploaduser);
			  rm.setCreatedate(createdate);
			 int i=rms.insert(rm);
			 if(i>0){
				 out.print("true");
				//刷新
					List<Booking> listrm=rms.findAll();
					request.getSession().setAttribute("list", listrm);
			 }else{
				 out.print("false");
			 }
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}

3.修改的Servlet

package servlet;
 
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 dao.BookingDao;
import entity.Booking;
 
public class updateServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public updateServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		
		BookingDao booking=new BookingDao();
	    	int id=Integer.parseInt(request.getParameter("id"));
	    	 int categoryId=Integer.parseInt(request.getParameter("categoryId"));
			  String title=request.getParameter("title");
			  String summary=request.getParameter("summary");
			  String uploaduser=request.getParameter("uploaduser");
			  String createdate=request.getParameter("createdate");
			  Booking rm=new Booking();
			      rm.setId(id);
				  rm.setCategoryId(categoryId);
				  rm.setTitle(title);
				  rm.setSummary(summary);
				  rm.setUploaduser(uploaduser);
				  rm.setCreatedate(createdate);
	    	int i=booking.update(rm);
			 if(i>0){
				//刷新
					List<Booking> listrm=booking.findAll();
					request.getSession().setAttribute("list", listrm);
					out.print("<script>alert('修改成功!!!');location.href='index.jsp';</script>");
			 }else{
				 out.print("<script>alert('修改失敗!!!');location.href='Update.jsp';</script>");
			 }
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}

4.刪除的Servlet

package servlet;
 
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 dao.BookingDao;
import entity.Booking;
 
public class deleteServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public deleteServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		BookingDao rms=new BookingDao();
		Booking rm=new Booking();
		int id=Integer.parseInt(request.getParameter("id"));
		rm.setId(id);
		int i=rms.delete(rm);
		if(i>0){
			List<Booking> listrm=rms.findAll();
			request.getSession().setAttribute("list", listrm);
			out.print("<script>alert('刪除成功!!!');location.href='index.jsp';</script>");
		}else{
			out.print("<script>alert('刪除失敗!!!');location.href='index.jsp';</script>");
		}
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}

8.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>selectServlet</servlet-name>
    <servlet-class>servlet.selectServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>insertServlet</servlet-name>
    <servlet-class>servlet.insertServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>updateServlet</servlet-name>
    <servlet-class>servlet.updateServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>deleteServlet</servlet-name>
    <servlet-class>servlet.deleteServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>idServlet</servlet-name>
    <servlet-class>servlet.idServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>selectServlet</servlet-name>
    <url-pattern>/selectServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>insertServlet</servlet-name>
    <url-pattern>/insertServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>updateServlet</servlet-name>
    <url-pattern>/updateServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>deleteServlet</servlet-name>
    <url-pattern>/deleteServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>idServlet</servlet-name>
    <url-pattern>/idServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>

需要注意的是下面段,在上面是web.xml中比較下面,

標簽聲明了與該servlet相應的匹配規則,每個 標簽代表1個匹配規則。含了兩個子元素 元素給出的Servlet名字必須是 在 元素中聲明過的Servlet的名字。 元素指定對應於Servlet的URL路 徑,該路徑是相對於Web應用程序上下文根的路徑。

<servlet-mapping>
   <servlet-name></servlet-name>
   <url-pattern></url-pattern>
</servlet-mapping>

9.再次寫JSP頁面

1.index.jsp 初始界面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
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>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  
  	<c:if test="${list==null}">
     <jsp:forward page="selectServlet"></jsp:forward>
    </c:if>
    <a href="insert.jsp"><input type="button" value="新增圖書"></a>
    
    <table border="1">
    	<tr><td>電子圖書列表</td></tr>
    	<tr><td>書品編號</td><td>書名</td><td>摘要</td><td>上傳人</td><td>上傳時間</td><td>操作</td></tr>
    	<c:forEach items="${list}" var="gd">
          <tr>
          	<td>${gd.categoryId}</td>
          	<td>${gd.title}</td>
          	<td>${gd.summary}</td>
          	<td>${gd.uploaduser}</td>
          	<td>${gd.createdate }</td>
          	<td><a href="idServlet?id=${gd.id}"><input type="button" value="修改"></a></td>
          	<td><a href="deleteServlet?id=${gd.id}"><input type="button" value="刪除"></a></td>
          </tr>
       </c:forEach>
    	
    </table>
  
  </body>
</html>

2.insert.jsp 添加頁面

<%@ 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></title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
 
	<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
	<script type="text/javascript">
	$(function(){
 
           $("#submit").click(function(){
                //非空驗證
                    var $form=$("form").serialize();
                    alert($form);
                  $.get("insertServlet",$form,function(data){
                      if(data=="true"){
                         alert("新增成功");
                         window.location="index.jsp";
                      }else{
                       alert("新增失敗");
                      }
                  });
       });
       });
	</script>
 
  </head>
  
  <body>
  	<form action="">
  		<h2>新增書本</h2>
  		書本編號:<input type="text" name="categoryId"><br>
  		書本名稱:<input type="text" name="title"><br>
  		摘要:<input type="text" name="summary"><br>
  		上傳人:<input type="text" name="uploaduser"><br>
  		上傳時間:<input type="text" name="createdate"><br>
  		<input type="button" id="submit" value="提交"><input type="reset" value="重置">
  	</form>
  
  </body>
</html>

3.Update.jsp 修改頁面

​ (1)這個是修改的主要

<%@ 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></title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
 
  </head>
  
  <body>
    	<form action="updateServlet">
  		<h2>修改書本</h2>
  		<input type="hidden" value="${idid}" name="id">
  		書本編號:<input type="text" name="categoryId"><br>
  		書本名稱:<input type="text" name="title"><br>
  		摘要:<input type="text" name="summary"><br>
  		上傳人:<input type="text" name="uploaduser"><br>
  		上傳時間:<input type="text" name="createdate"><br>
  		<input type="submit" id="submit" value="提交"><input type="reset" value="重置">
  	</form>
  </body>
</html>


(2)這個idServlet是我后面出現的BUG,我現在只能給又加了一個Servlet

package servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class idServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public idServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		int id=Integer.parseInt(request.getParameter("id"));
		request.getSession().setAttribute("idid", id);
		response.sendRedirect("Update.jsp");
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}


10. 最后這個是在瀏覽器中顯示的效果,這個是查詢效果,查詢全表如下

1.查詢

[外鏈圖片轉存失敗(img-wKfi8YM4-1567778008411)(https://cdn.jsdelivr.net/gh/Zevs6/blogimg/img/201803292306105211)]

2.增加

3.修改(接下里我們把剛才我們添加的數據修改)

4.刪除(這個效果可能不是很明顯,但為了界面我還是把它給截圖下來了)

​ 我把剛才我們上面操作的添加和修改給刪除掉看看效果!

[外鏈圖片轉存失敗(img-UJdB1eFD-1567778008412)(https://cdn.jsdelivr.net/gh/Zevs6/blogimg/img/201803292353239561)]

好了,這個項目也算了做完了,是個完整的,雖然在往數據庫傳數據的時候出現了中文亂碼,但是我會去調這個BUG的,但至少功能實現了,以上就是這個項目了,雖然在有些地方大家看到的效果不是跟明顯,如果本篇文章看了對大家有幫助,麻煩大家點個贊,謝謝,如果對本篇有疑問或者是想要我一步一步做給你看,加我QQ3506346737(備注:CSDN博客+QQ名字),很期待您的好友申請,也很期待大家對本篇文章的一些改進建議,謝謝

附源碼獲取下載地址:百度網盤。下載代碼后遇到問題及時聯系本人,盡快修正錯誤。

鏈接:https://pan.baidu.com/s/1nlOSG10a0dW72qeeUKrS2g
提取碼:ycqr


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM