jsp页面实现增删改查
时间: 2023-12-22 09:04:52 浏览: 142
jsp实现增删查改
JSP页面可以通过与后端代码交互来实现增删改查的功能。以下是一个简单的示例:
1. 实现查询功能:
```jsp
<%@ page import="java.sql.*" %>
<%
// 连接数据库
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
// 执行查询语句
String sql = "SELECT * FROM students";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// 显示查询结果
while (rs.next()) {
out.println("ID: " + rs.getInt("id") + "<br>");
out.println("Name: " + rs.getString("name") + "<br>");
out.println("Age: " + rs.getInt("age") + "<br>");
out.println("<br>");
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
%>
```
2. 实现添加功能:
```jsp
<%@ page import="java.sql.*" %>
<%
// 获取表单数据
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
// 连接数据库
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
// 执行插入语句
String sql = "INSERT INTO students (name, age) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.executeUpdate();
// 关闭连接
pstmt.close();
conn.close();
%>
```
3. 实现修改功能:
```jsp
<%@ page import="java.sql.*" %>
<%
// 获取表单数据
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
// 连接数据库
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
// 执行更新语句
String sql = "UPDATE students SET name = ?, age = ? WHERE id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setInt(3, id);
pstmt.executeUpdate();
// 关闭连接
pstmt.close();
conn.close();
%>
```
4. 实现删除功能:
```jsp
<%@ page import="java.sql.*" %>
<%
// 获取表单数据
int id = Integer.parseInt(request.getParameter("id"));
// 连接数据库
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
// 执行删除语句
String sql = "DELETE FROM students WHERE id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
// 关闭连接
pstmt.close();
conn.close();
%>
```
阅读全文