帮我用java代码写一个serverlet可以对数据库进行增删改查
时间: 2024-01-02 16:02:30 浏览: 77
好的,下面是一个简单的Java Servlet示例代码,可以进行数据库的增删改查操作。假设数据库使用MySQL,并且已经连接成功。
```java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DBServlet")
public class DBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection conn;
private Statement stmt;
public void init() throws ServletException {
// 连接数据库
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// 查询数据库
String sql = "select * from user";
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
while (rs.next()) {
out.println("id=" + rs.getInt("id") + ", name=" + rs.getString("name") + ", age="
+ rs.getInt("age") + "<br>");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// 插入数据
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String sql = "insert into user(name,age) values('" + name + "'," + age + ")";
try {
stmt.executeUpdate(sql);
out.println("插入成功");
} catch (SQLException e) {
e.printStackTrace();
}
// 更新数据
int id = Integer.parseInt(request.getParameter("id"));
sql = "update user set name='" + name + "', age=" + age + " where id=" + id;
try {
stmt.executeUpdate(sql);
out.println("更新成功");
} catch (SQLException e) {
e.printStackTrace();
}
// 删除数据
id = Integer.parseInt(request.getParameter("id"));
sql = "delete from user where id=" + id;
try {
stmt.executeUpdate(sql);
out.println("删除成功");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void destroy() {
// 关闭数据库连接
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们使用了`init()`方法来连接数据库,使用`doGet()`方法来查询数据,使用`doPost()`方法来插入、更新和删除数据,使用`destroy()`方法来关闭数据库连接。其中,`request.getParameter()`方法用于获取前端页面传来的参数,`stmt.executeUpdate()`方法用于执行增删改操作,`stmt.executeQuery()`方法用于执行查询操作。
需要注意的是,上面的代码仅仅是一个简单的示例,实际项目中需要考虑更多的异常处理、安全性等问题。
阅读全文