11.22判断是否存在

发布时间 2023-12-18 18:44:31作者: new菜鸟

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.naming.*" %>
<%@ page import="javax.*" %>
<html>
<body>

<%
request.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet existingRecord = null;
String message = "";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/demo?useSSL=false";
String name1 = "root";
String password = "123456";
conn = DriverManager.getConnection(url, name1, password);
String query = "SELECT * FROM teacher WHERE id=?";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, id);
existingRecord = pstmt.executeQuery();

if (existingRecord.next()) {
response.sendRedirect("teacher2.jsp");

} else {
out.println("编号 " + id + " 不存在。");
}

} catch (SQLException | ClassNotFoundException e) {
System.out.println("发生错误: " + e.getMessage());
e.printStackTrace();
} finally {
try {
if (existingRecord != null) {
existingRecord.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("关闭资源时发生错误: " + e.getMessage());
}
}
if (message.equals("插入成功!")) {

}
%>


</body>
</html>