11.14 插入

<%@ 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");
String name = request.getParameter("name");
String number = request.getParameter("number");
String name1 = request.getParameter("name1");

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 name11 = "root";
String password = "123456";
conn = DriverManager.getConnection(url, name11, password);
String query = "SELECT * FROM class1 WHERE id=?";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, id);
existingRecord = pstmt.executeQuery();

if (existingRecord.next()) {
// 学号已存在,不执行插入操作
System.out.println("编号 " + id + " 已存在,不能重复添加。");
} else {
String sql = "insert into class1(id,name,number,name1) values(?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, name);
pstmt.setString(3,number);
pstmt.setString(4,name1);


int rowsAffected = pstmt.executeUpdate();
if (rowsAffected > 0) {
message = "插入成功!";
} else {
message = "插入失败";
}
}

} 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());
}
}

%>


</body>
</html>

posted @   new菜鸟  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示