經過一個綜合型的例子加深對JDBC操做數據庫的增、刪、改、查的運用。javascript
經典的圖書信息錄入實例css
設計數據庫html
CREATE TABLE `tb_books` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, `price` double NOT NULL, `bookCount` int(10) unsigned NOT NULL, `author` varchar(45) NOT NULL, PRIMARY KEY (`id`) )
寫一個Book類對圖書信息進行封裝java
package com.lixiyu; public class Book { private int id; private String name; private double price; private int bookCount; private String author; 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 double getPrice(){ return price; } public void setPrice(double price){ this.price=price; } public int getbookCount(){ return bookCount; } public void setbookCount(int bookCount){ this.bookCount=bookCount; } public String getAuthor(){ return author; } public void setAuthor(String author){ this.author=author; } }
添加(insert)圖書信息操做mysql
建立AddBook.jsp頁面,用於對添加圖書信息進行處理web
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@page import="java.sql.Connection"%> <%@page import="java.sql.DriverManager"%> <%@page import="java.sql.PreparedStatement"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>Insert title here</title> </head> <body> <%request.setCharacterEncoding("UTF-8"); %> <jsp:useBean id="book" class="com.lixiyu.Book"></jsp:useBean> <jsp:setProperty property="*" name="book"/> <% try{ Class.forName("com.mysql.jdbc.Driver");//加載數據庫驅動,註冊到驅動管理器 String url="jdbc:mysql://localhost:3306/db_test";//數據庫鏈接字符串 String username="root";//數據庫用戶名 String password="lixiyu";//數據庫密碼 Connection conn=DriverManager.getConnection(url,username,password);//建立Connection鏈接 String sql="insert into tb_books(name,price,bookCount,author)values(?,?,?,?)";//添加圖書信息sql語句 PreparedStatement ps=conn.prepareStatement(sql);//獲取PreparedStatement ps.setString(1,book.getName());//對SQL語句中的第1個參數賦值 ps.setDouble(2,book.getPrice()); ps.setInt(3,book.getbookCount()); ps.setString(4,book.getAuthor());//對SQL語句中的第4個參數賦值 int row=ps.executeUpdate();//執行更新操做,返回所影響的行數 if(row>0){ out.print("成功添加了"+row+"條數據"); } ps.close(); conn.close(); }catch(Exception e){ out.print("圖書信息添加失敗!"); e.printStackTrace(); } %> </body> <a href="insert.jsp">返回</a> </html>
建立insert.jsp,用於建立添加圖書信息所需的表單sql
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>添加圖書信息</title> <script type="text/javascript"> function check(form){ with(form){ if(name.value == ""){ alert("圖書名稱不能爲空"); return false; } if(price.value == ""){ alert("價格不能爲空"); return false; } if(author.value == ""){ alert("做者不能爲空"); return false; } return true; } } </script> </head> <body> <form action="AddBook.jsp" method="post" onsubmit="return check(this);"> <table align="center" width="450"> <tr> <td align="center" colspan="2"> <h2>添加圖書信息</h2> <hr> </td> </tr> <tr> <td align="right">圖書名稱:</td> <td><input type="text" name="name" /></td> </tr> <tr> <td align="right">價 格:</td> <td><input type="text" name="price" /></td> </tr> <tr> <td align="right">數 量:</td> <td><input type="text" name="bookCount" /></td> </tr> <tr> <td align="right">做 者:</td> <td><input type="text" name="author" /></td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="添 加"> </td> </tr> </table> </form> </body> </html>
最後運行數據庫
成功:app
查詢(select)圖書信息操做jsp
建立FindServlet的servlet對象用於查詢全部圖書的信息。編寫doGet()方法,創建數據庫鏈接,並將全部查詢數據集合放置HttpServletRequest對象中,將請求轉發到jsp頁面中:
package com.lixiyu; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class FindServlet */ public class FindServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FindServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub try{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/db_test"; String username="root"; String password="lixiyu"; Connection conn=DriverManager.getConnection(url,username,password); Statement stmt=conn.createStatement();//獲取statement對象 String sql="select * from tb_books"; ResultSet rs=stmt.executeQuery(sql); List<Book> list=new ArrayList<Book>();//實例化list對象 while(rs.next()){ Book book=new Book(); book.setId(rs.getInt("id"));//對id屬性賦值 book.setName(rs.getString("name")); book.setPrice(rs.getDouble("price")); book.setbookCount(rs.getInt("bookCount")); book.setAuthor(rs.getString("author")); list.add(book);//將圖書對象添加到集合中 } request.setAttribute("list", list);//將圖書集合放置到request中 rs.close();//關閉ResultSet stmt.close();//關閉Statement conn.close();//關閉Connection }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); } request.getRequestDispatcher("book_list.jsp").forward(request, response);//請求轉發到book_List.jsp } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
在web.xml中添加映射:
<welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>FindServlet</display-name> <servlet-name>FindServlet</servlet-name> <servlet-class>com.lixiyu.FindServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FindServlet</servlet-name> <url-pattern>/FindServlet</url-pattern> </servlet-mapping>
建立book_list.jsp頁面,用於顯示查詢到的全部圖書信息
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="java.util.List"%> <%@page import="com.lixiyu.Book"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>全部圖書信息</title> <style type="text/css"> td{font-size: 12px;} h2{margin: 0px} </style> </head> <body> <table align="center" width="450" border="1" height="180" bordercolor="white" bgcolor="" cellpadding="1" cellspacing="1"> <tr bgcolor="white"> <td align="center" colspan="5"> <h2>全部圖書信息</h2> </td> </tr> <tr align="center" bgcolor="#e1ffc1" > <!-- <td><b>ID</b></td>--> <td><b>圖書名稱</b></td> <td><b>價格</b></td> <td><b>數量</b></td> <td><b>做者</b></td> </tr> <% // 獲取圖書信息集合 List<Book>list = (List<Book>)request.getAttribute("list"); // 判斷集合是否有效 if(list == null || list.size() < 1){ out.print("沒有數據!"); }else{ // 遍歷圖書集合中的數據 for(Book book : list){ %> <tr align="center" bgcolor="white"> <!--<td><%=book.getId()%></td>--> <td><%=book.getName()%></td> <td><%=book.getPrice()%></td> <td><%=book.getbookCount()%></td> <td><%=book.getAuthor()%></td> <td> <form action="UpdateServlet" method="post" onsubmit="return check(this);"> <input type="hidden" name="id" value="<%=book.getId()%>"> <input type="text" name="bookCount" size="3"> </form> </tr> <% } } %> </table> <br> </body> </html>
建立index.jsp主頁,用於請求查看全部圖書信息:
<body> <a href="FindServlet">查看全部圖書</a> </body>
運行該實例
修改(update)圖書信息操做
在book_list.jsp中添多一列修改:
<td> <form action="UpdateServlet" method="post" onsubmit="return check(this);"> <input type="hidden" name="id" value="<%=book.getId()%>"> <input type="text" name="bookCount" size="3"> <input type="submit" value="修改"> </form></td>
建立UpdateServlet.jsp編寫doPost方法對圖書信息請求進行處理:
package com.lixiyu; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class UpdateServlet */ public class UpdateServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id = Integer.valueOf(request.getParameter("id")); int bookCount = Integer.valueOf(request.getParameter("bookCount")); try { // 加載數據庫驅動,註冊到驅動管理器 Class.forName("com.mysql.jdbc.Driver"); // 數據庫鏈接字符串 String url = "jdbc:mysql://localhost:3306/db_test"; // 數據庫用戶名 String username = "root"; // 數據庫密碼 String password = "lixiyu"; // 建立Connection鏈接 Connection conn = DriverManager.getConnection(url,username,password); // 更新SQL語句 String sql = "update tb_books set bookcount=? where id=?"; // 獲取PreparedStatement PreparedStatement ps = conn.prepareStatement(sql); // 對SQL語句中的第一個參數賦值 ps.setInt(1, bookCount); // 對SQL語句中的第二個參數賦值 ps.setInt(2, id); // 執行更新操做 ps.executeUpdate(); // 關閉PreparedStatement ps.close(); // 關閉Connection conn.close(); } catch (Exception e) { e.printStackTrace(); } // 重定向到FindServlet response.sendRedirect("FindServlet"); } }
添加xml映射
<servlet> <display-name>UpdateServlet</display-name> <servlet-name>UpdateServlet</servlet-name> <servlet-class>com.lixiyu.UpdateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UpdateServlet</servlet-name> <url-pattern>/UpdateServlet</url-pattern> </servlet-mapping>
運行後
刪除(delete)圖書信息操做
編寫刪除操做的servlet,命名爲DeleteServlet:
package com.lixiyu; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class DeleteServlet */ public class DeleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取圖書id int id = Integer.valueOf(request.getParameter("id")); try { // 加載數據庫驅動,註冊到驅動管理器 Class.forName("com.mysql.jdbc.Driver"); // 數據庫鏈接字符串 String url = "jdbc:mysql://localhost:3306/db_test"; // 數據庫用戶名 String username = "root"; // 數據庫密碼 String password = "lixiyu"; // 建立Connection鏈接 Connection conn = DriverManager.getConnection(url,username,password); // 刪除圖書信息的SQL語句 String sql = "delete from tb_books where id=?"; // 獲取PreparedStatement PreparedStatement ps = conn.prepareStatement(sql); // 對SQL語句中的第一個佔位符賦值 ps.setInt(1, id); // 執行更新操做 ps.executeUpdate(); // 關閉PreparedStatement ps.close(); // 關閉Connection conn.close(); } catch (Exception e) { e.printStackTrace(); } // 重定向到FindServlet response.sendRedirect("FindServlet"); } }
添加xml映射:
<servlet> <description></description> <display-name>DeleteServlet</display-name> <servlet-name>DeleteServlet</servlet-name> <servlet-class>com.lixiyu.DeleteServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DeleteServlet</servlet-name> <url-pattern>/DeleteServlet</url-pattern> </servlet-mapping> </web-app>
整合CRUD操做
在前面book_list.jsp頁面中進行整合:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="java.util.List"%> <%@page import="com.lixiyu.Book"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>全部圖書信息</title> <style type="text/css"> td{font-size: 12px;} h2{margin: 0px} </style> </head> <body> <table align="center" width="450" border="1" height="180" bordercolor="white" bgcolor="" cellpadding="1" cellspacing="1"> <tr bgcolor="white"> <td align="center" colspan="5"> <h2>全部圖書信息</h2> </td> </tr> <tr align="center" bgcolor="#e1ffc1" > <!-- <td><b>ID</b></td>--> <td><b>圖書名稱</b></td> <td><b>價格</b></td> <td><b>數量</b></td> <td><b>做者</b></td> <td><b>修改數量</b></td> <td><b>刪 除</b></td> </tr> <% // 獲取圖書信息集合 List<Book>list = (List<Book>)request.getAttribute("list"); // 判斷集合是否有效 if(list == null || list.size() < 1){ out.print("沒有數據!"); }else{ // 遍歷圖書集合中的數據 for(Book book : list){ %> <tr align="center" bgcolor="white"> <!--<td><%=book.getId()%></td>--> <td><%=book.getName()%></td> <td><%=book.getPrice()%></td> <td><%=book.getbookCount()%></td> <td><%=book.getAuthor()%></td> <td> <form action="UpdateServlet" method="post" onsubmit="return check(this);"> <input type="hidden" name="id" value="<%=book.getId()%>"> <input type="text" name="bookCount" size="3"> <input type="submit" value="修改"> </form> </td> <td><a href="DeleteServlet?id=<%=book.getId() %>">刪除</a> </td> </tr> <% } } %> </table> <br> <center> <form action="insert.jsp" method="post" onsubmit="return check(this);"> <input type="submit" name="" value="添加數據" > </form></center> </body> </html>
將前面AddBook.jsp中的頁面連接進行修改
<a href="FindServlet">返回</a>
所以整個操做都回歸到book_list.jsp來顯示了
運行
CRUD操做整合到一個頁面顯示:
此次JDBC先寫到這,下次有時間再總結一下批處理、調用存儲過程、分頁查詢的相關操做。