Miss Zhu 2022-02-13 08:39:08 阅读数:106
The previous two articles are the preparation work for the implementation of modification , At this time, you can click... On the modification page “ preservation ” Button to modify .
Two hidden fields are required , A type of save operation , namely “update”, A preservation id The value of :
<form class="form-horizontal" action="stu">
<input type="hidden" name="type" value="update" />
<input type="hidden" name="id" value="<%=stu.getId()%>" />
<!-- Other codes are omitted -->
</form>
Back end StudentController Class , Of doGet Method , Add another else if:
else if (type.equals("update")) {
update(request, response);
}
Add a new one update Method :
public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String gender = request.getParameter("gender");
int age = Integer.parseInt(request.getParameter("age"));
Student stu = new Student();
stu.setId(id);
stu.setName(name);
stu.setGender(gender);
stu.setAge(age);
StudentDao stuDao = new StudentDao();
boolean flag = stuDao.update(stu);
if (flag) {
response.sendRedirect("stu");
} else {
// Error page
}
}
stay StudentDao Add a udpate Method :
public boolean update(Student stu) {
int rs = 0;// Indicates execution sql Result of statement
// jdbc Seven steps
// 1. Will database jar Package copy to lib Under the folder
try {
// 2. The load driver
Class.forName("com.mysql.jdbc.Driver");
// 3. Establishing a connection
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/school_sk1?characterEncoding=utf-8", "root", "123456");
// 4. establish SQL actuator
Statement stat = conn.createStatement();
// 5. perform sql sentence
String sql = "update student set name='" + stu.getName() + "',gender='" + stu.getGender() + "',age="
+ stu.getAge() + " where id=" + stu.getId();
rs = stat.executeUpdate(sql);
// 6. Processing results
// 7. Close the connection
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs > 0;
}
copyright:author[Miss Zhu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130839063790.html