JDBC操作數據庫


1. 添加數據

通過JDBC向數據庫添加數據,可以使用INSERT語句實現插入數據SQL語句,對於SQL語句中的參數可以使用占位符“?"代替,然后通過PreparedStatement對其賦值並執行SQL。

例1.1 創建Web項目,然后通過JDBC實現圖書信息添加功能。

(1)在MySQL數據庫中創建圖書信息表books,其結構如下圖所示。

(2)創建名稱為Book的類,用於封裝圖書對象信息。關鍵代碼如下:

package com.cn.database;

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;
    }
}

(3)創建index.jsp頁面,它是程序中的主頁,用於放置添加圖書信息所需要的表單,該表單提交到AddBook.jsp頁面進行處理。關鍵代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
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 'index.jsp' starting page</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="AddBook.jsp" method="post" onsubmit="return check(this);">
        <table align="center" width="450">
            <tr>
                <td align="center" colspan="2">
                    <h2>添加圖書信息</h2>
                </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>

(4)創建AddBook.jsp頁面,用於對添加圖書信息請求進行處理,該頁面通過JDBC將所提交的圖書信息數據寫入數據庫中。關鍵代碼如下:

<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
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 'AddBook.jsp' starting page</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>
    <%request.setCharacterEncoding("GBK"); %>
    <jsp:useBean id="book" class="com.cn.database.Book"></jsp:useBean>
    <jsp:setProperty property="*" name="book"/>
    <%
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1234");
            String sql="insert into books(name,price,bookCount,author) values(?,?,?,?)";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1, book.getName());
            ps.setDouble(2, book.getPrice());
            ps.setInt(3, book.getBookCount());
            ps.setString(4, book.getAuthor());
            int row = ps.executeUpdate(); //執行更新操作,返回所影響的行數
            if(row > 0){
                out.print("成功添加了"+row+"條數據!");
            }
            ps.close();  //關閉PrepareStatement,釋放資源
            conn.close();
        }catch(Exception e){
            out.print("圖書信息添加失敗!");
            e.printStackTrace();            
        }
     %>
     <br>
     <a href="index4.jsp">返回</a>
  </body>
</html>

在AddBook.jsp頁面中,首先通過<jsp:useBean>實例化JavaBean對象Book,並通過<jsp:setProperty>對Book對象中的屬性賦值,在構建了圖書對象后通過JDBC將圖書信息寫入到數據庫中。

2. 查詢數據

使用JDBC查詢數據與添加數據的流程基本相同,但執行查詢數據操作后需要通過一個對象來裝載查詢結果集,這個對象就是ResultSet對象。

例2.1 創建Web項目,通過JDBC查詢圖書信息表中的圖書信息,並將其顯示在JSP頁面中。

(1)創建名稱為Book的類,用於封裝圖書信息,代碼同例1.1。

(2)創建名稱為FindServlet的Servlet對象,用於查詢所有圖書信息。在此Servlet中, 編寫doGet()方法,建立數據庫連接,並將所查詢的數據集合放置到HttpServletRequest對象中,將請求轉發到JSP頁面。關鍵代碼如下:

package com.cn.gao;

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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.gao.Book;

public class FindServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1234");
            String sql = "select* from books";
            Statement sta = conn.createStatement();
            ResultSet rs = sta.executeQuery(sql);
            List<Book> list = new ArrayList<Book>();
            while(rs.next()){
                Book book = new Book();
                book.setId(rs.getInt("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);   //將所查詢的數據集合放置到HttpServletRequest對象中
            rs.close();
            sta.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        request.getRequestDispatcher("book_list.jsp").forward(request, response); //請求轉發到book_list.jsp
    }

}

(3)創建book_list.jsp頁面,用於顯示所有圖書信息。關鍵代碼如下:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GBK"%>
<%@ page import="java.util.*" %>
<%@ page import="com.cn.gao.*" %>
<!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>
    <form action="" method="post">
        <table align="center" width="450" border="1">
            <tr>
                <td align="center" colspan="5">所有圖書信息</td>
            </tr>
            <tr align="center">
                <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">
                <td><%=book.getId()%></td>
                <td><%=book.getName()%></td>
                <td><%=book.getPrice()%></td>
                <td><%=book.getBookCount()%></td>
                <td><%=book.getAuthor()%></td>
            </tr>
            <%
                    }
                }
             %>
        </table>
    </form>
</body>
</html>

由於FindServlet將查詢的所有圖書信息集合放置到了request中,所以在book_list.jsp中可以通過request的getAttribute()方法獲取到這一集合對象。實例中在獲得所有圖書信息集合后,通過for循環遍歷所有圖書信息集合,並將其輸出到頁面中。

(4) 創建showbook.jsp頁面,該頁面為程序中的主頁,在該頁面中編寫一個導航鏈接,用於請求查看所有圖書信息。關鍵代碼如下:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!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>
    <table widht="450">
        <tr>
            <td align="center">
                <h2><a href="FindServlet">查看所有圖書</a></h2>
            <td>
        </tr>
    </table>
</body>
</html>

部署並運行程序后,將打開showbook.jsp頁面,單擊“查看所有圖書”鏈接后,可以查看到從數據庫中查詢的所有圖書信息。

3. 修改數據

使用JDBC修改數據庫中的數據,其操作方法與添加數據相似,只不過修改數據需要使用UPDATE語句實現。

在實際的開發中,通常情況下都是由程序傳遞SQL語句中的參數,所以修改數據也需要使用PreparedStatement對象進行操作。

 例3.1 在查詢所有圖書信息的頁面中,添加修改圖書數量的表單,通過Servlet修改數據庫中的圖書數量。

(1)在book_list.jsp頁面中增加修改圖書數量的表單,將該表單的提交地址設置為UpdateServlet。關鍵代碼如下:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GBK"%>
<%@ page import="java.util.*" %>
<%@ page import="com.cn.gao.*" %>
<!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>
    <form action="" method="post">
        <table align="center" width="450" border="1">
            <tr>
                <td align="center" colspan="6">所有圖書信息</td>
            </tr>
            <tr align="center">
                <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>
            </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">
                <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>
            </tr>
            <%
                    }
                }
             %>
        </table>
    </form>
</body>
</html>

在修改圖書信息的表單中,主要包含兩個屬性信息,分別為圖書id與圖書數量bookCount,因為修改圖書數量時需要明確指定圖書的id作為修改的條件,否則,將會修改所有圖書信息記錄。

技巧:由於圖書id屬性並不需要顯示在表單中,而在圖書信息的修改過程中又需要獲取這個值,所以,將id對應文本框<input>中的type屬性設置為hidden,使之在表單中構成一個隱藏於,從而實現實際的業務需求。

(2)創建修改圖書信息的Servlet對象,其名稱為UpdateServlet。由於表單提交請求類型為post,所以在UpdateServlet中編寫doPost()方法,對修改圖書信息請求進行處理。關鍵代碼如下:

package com.cn.gao;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UpdateServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        int bookCount = Integer.parseInt(request.getParameter("bookCount"));
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1234");
            String sql = "update books set bookCount=? where id=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, bookCount);
            ps.setInt(2, id);
            ps.executeUpdate();
            ps.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.sendRedirect("FindServlet");  //重定向到FindServlet
    }

}

 4. 刪除數據

例4.1 在查詢所有圖書信息的頁面中,添加刪除圖書信息的超鏈接,通過Servlet實現對數據的刪除操作。

(1)在book_list.jsp頁面中,增加刪除圖書信息的超鏈接,將鏈接地址指向DeleteServlet。關鍵代碼如下:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GBK"%>
<%@ page import="java.util.*" %>
<%@ page import="com.cn.gao.*" %>
<!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>
    <form action="" method="post">
        <table align="center" width="600" border="1">
            <tr>
                <td align="center" colspan="7">所有圖書信息</td>
            </tr>
            <tr align="center">
                <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">
                <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>
                    <form action="DeleteServlet" method="post" onsubmit="return check(this);">
                        <input type="hidden" name="id" value="<%=book.getId() %>">
                        <input type="submit" value="刪  除">
                    </form>
                </td>
或者:

<td>
<a href="DeleteServerlet?id=<%book.getId()%>>刪除</a>
</td>

            </tr>
            <%
                    }
                }
             %>
        </table>
    </form>
</body>
</html>

在刪除數據信息操作中,需要傳遞所要刪除的圖書對象,因此,在刪除圖書信息的超鏈接中加入圖書id值。

技巧:在Java Web開發中,JSP頁面中的超鏈接可以帶有參數,器操作方式通過在超鏈接后加入“?”實現。

(2)編寫處理刪除圖書信息的Servlet,其名稱為DeleteServlet。在doPost()(或doGet())方法中,編寫刪除圖書信息的方法。關鍵代碼如下:

package com.cn.gao;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DeleteServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1234");
            String sql = "delete from books where id=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            ps.executeUpdate();
            ps.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.sendRedirect("FindServlet");
    }

}

 


免責聲明!

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



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