提問未說明使用框架(原生 JDBC / Spring JDBC / MyBatis / Hibernate / JPA)及數據庫類型。
<%@ page import="java.sql.*" %>
<%
String url = "jdbc:mysql://localhost:3306/db?useSSL=false";
String user = "root", pwd = "123456";
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection conn = DriverManager.getConnection(url, user, pwd)) {
// 刪除
String delSql = "DELETE FROM history WHERE id=?";
try (PreparedStatement ps = conn.prepareStatement(delSql)) {
ps.setInt(1, Integer.parseInt(request.getParameter("id")));
ps.executeUpdate();
}
// 新增
String insSql = "INSERT INTO history(content, create_time) VALUES(?, NOW())";
try (PreparedStatement ps = conn.prepareStatement(insSql)) {
ps.setString(1, request.getParameter("content"));
ps.executeUpdate();
}
} catch (Exception e) { e.printStackTrace(); }
%>
生產環境必須:連接池、事務管理、參數校驗、異常統一處理、防 SQL 注入(已用 PreparedStatement)。