雖然現代開發推薦分層架構,但針對簡單專案或快速原型,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) {}
}
%>
PreparedStatement 參數化查詢。ResultSet/Statement/Connection 必須在 finally 區塊關閉,或採用 try-with-resources (JDK 7+)。