首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

使用 Java Servlet 與 PreparedStatement 實作資料庫新增功能

     編輯:Java 相關知識

前言

本文為「使用 Servlet 進行資料庫查詢、新增、更新與刪除」系列教學的第二篇。若您已閱讀上一篇「從資料庫顯示記錄」,本篇將輕鬆好懂許多,因為 90% 的程式碼結構相似。建議先回顧前一篇文章,其中詳細說明了資料庫連線、DSN 設定等基礎概念。

為什麼要使用 PreparedStatement?

雖然上一篇介紹的 Statement 類別也能執行 INSERT 語法,但效率較低且未經最佳化。PreparedStatement 位於 java.sql 套件,允許我們建立「預編譯」的 SQL 查詢,並在執行時動態綁定參數,不僅效能更佳,也能有效防止 SQL 注入攻擊。雖然並非所有資料庫廠商都完整支援,但養成使用習慣仍是最佳實務。

PreparedStatement 核心操作

取得 PreparedStatement 物件

String sql = "INSERT INTO Names(first_name, last_name) VALUES (?,?)";
PreparedStatement ps = con.prepareStatement(sql);

SQL 字串中的 ? 為參數佔位符,索引從左至右為 1、2...。使用 setXxx(int parameterIndex, Object value) 系列方法設定值:

ps.setString(1, "First Name");
ps.setString(2, "Last Name");
ps.executeUpdate(); // 執行 INSERT、UPDATE、DELETE

查詢類語句請改用 executeQuery()。

實作 InsertServlet

在 /APP_NAME/WEB-INF/classes/com/stardeveloper/servlets/db/ 建立 InsertServlet.java。以下為核心程式碼重點:

doGet():顯示輸入表單

public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("
"); out.println("First Name:
"); out.println("Last Name:

"); out.println(""); out.println(""); out.println("
"); out.close(); }

doPost():處理新增與顯示

public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    
    // 1. 取得並驗證參數
    String first = req.getParameter("first").trim();
    String last = req.getParameter("last").trim();
    boolean proceed = (first != null && last != null 
                    && first.length() > 0 && last.length() > 0);

    Connection con = null;
    PreparedStatement ps = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {
        // 2. 建立資料庫連線
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con = DriverManager.getConnection("jdbc:odbc:odbc_exmp");

        // 3. 準備 INSERT 預編譯語句
        String sql = "INSERT INTO Names(first_name, last_name) VALUES (?,?)";
        ps = con.prepareStatement(sql);
        stmt = con.createStatement(); // 用於後續查詢顯示

        // 4. 執行新增
        if (proceed) {
            ps.setString(1, first);
            ps.setString(2, last);
            ps.executeUpdate();
        }

        // 5. 查詢並顯示所有記錄(含剛新增的)
        rs = stmt.executeQuery("SELECT * FROM Names");
        out.println("
ID\tFirst Name\tLast Name\n");
        while (rs.next()) {
            out.println(rs.getObject(1) + "\t" 
                      + rs.getObject(2) + "\t\t" 
                      + rs.getObject(3));
        }
        out.println("
"); } catch (SQLException | ClassNotFoundException e) { throw new ServletException(e); } finally { // 6. 關閉資源(逆序關閉) try { if (rs != null) rs.close(); } catch (SQLException ignored) {} try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {} try { if (ps != null) ps.close(); } catch (SQLException ignored) {} try { if (con != null) con.close(); } catch (SQLException ignored) {} } out.close(); }

執行與測試

啟動應用伺服器(如 Tomcat 4.0),瀏覽器存取 https://localhost:8080/star/servlet/com.stardeveloper.servlets.db.InsertServlet 即可看到表單與資料列表。

總結

  • 掌握 PreparedStatement 建立預編譯 SQL、綁定參數、執行更新的完整流程。
  • 實作一個完整的 Servlet:doGet 顯示表單,doPost 處理新增與即時回饋查詢結果。
  • 資源管理採用 try-catch-finally 確保連線、Statement、ResultSet 正確關閉。

本範例使用 Microsoft Access 資料庫 (odbc_exmp.mdb) 與 JDBC/ODBC Bridge 驅動程式(JDK 內建)。下一篇將介紹如何使用 PreparedStatement 實作資料更新功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved