基于HTML+Servlet+JAVAWeb+MYSQL数据库的大麦网(增删改)
由于问题描述不具体,我将提供一个使用Servlet和JDBC操作MySQL数据库的简单示例。假设我们有一个名为douban
的数据库表,它有id
, name
和 rating
三个字段。
首先,确保你已经添加了MySQL JDBC驱动的依赖到你的项目中。
// DoubanDAO.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DoubanDAO {
private Connection connect = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public DoubanDAO() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/douban", "username", "password");
}
public void addMovie(Douban movie) throws SQLException {
String query = "INSERT INTO douban (name, rating) VALUES (?, ?)";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setString(1, movie.getName());
preparedStatement.setDouble(2, movie.getRating());
preparedStatement.executeUpdate();
}
public void updateMovie(Douban movie) throws SQLException {
String query = "UPDATE douban SET name = ?, rating = ? WHERE id = ?";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setString(1, movie.getName());
preparedStatement.setDouble(2, movie.getRating());
preparedStatement.setInt(3, movie.getId());
preparedStatement.executeUpdate();
}
public void deleteMovie(int id) throws SQLException {
String query = "DELETE FROM douban WHERE id = ?";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
}
public Douban getMovie(int id) throws SQLException {
String query = "SELECT * FROM douban WHERE id = ?";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setInt(1, id);
resultSet = preparedStatement.
评论已关闭