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

JSP 混合 SQL 語句操作資料庫完整範例

     編輯:關於JSP

雖然現代開發推薦分層架構,但針對簡單專案或快速原型,JSP 直接嵌入 SQL 仍有參考價值。以下為增刪改查完整範例。

新增

String sql = "INSERT INTO allorder VALUES('" + orderid + "','" + bookid + "','" + amount + "','" + username + "')";
int result = stmt.executeUpdate(sql);
if (result == 1) response.sendRedirect("index.jsp");
else response.sendRedirect("detail.jsp");

刪除

String sql = "DELETE FROM allorder WHERE id='" + orderid + "'";
int result = stmt.executeUpdate(sql);
if (result == 1) response.sendRedirect("index.jsp");
else out.println("shopCar.jsp");

修改

同理使用 UPDATE ... SET ... WHERE ...,配合 executeUpdate()。

查詢與顯示

<% while (rs.next()) { %>
    <tr>
        <td><%= rs.getString("id") %></td>
        <td><%= rs.getString("pic") %></td>
        <td><%= rs.getString("name") %></td>
        <td><%= rs.getString("price") %></td>
        <td><%= rs.getString("amount") %></td>
        <td>
            <input type="button" value="刪除"
                onclick="window.location.href='delete.jsp?orderid=<%= rs.getString("id") %>'">
        </td>
    </tr>
<% } %>

資源關閉與異常處理

<%
} catch (SQLException e) {
    e.printStackTrace();
    out.println("資料庫連線錯誤");
    System.exit(0);
} finally {
    try { if (stmt != null) stmt.close(); } catch (Exception ignore) {}
    try { if (conn != null) conn.close(); } catch (Exception ignore) {}
}
%>

安全與最佳實踐提醒

  • SQL 注入風險:字串拼接 SQL 極易遭注入,正式專案務必使用 PreparedStatement 參數化查詢。
  • 資源洩漏:ResultSet/Statement/Connection 必須在 finally 區塊關閉,或採用 try-with-resources (JDK 7+)。
  • 分層架構:建議將資料存取邏輯移至 DAO 層,JSP 僅負責顯示。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved