mysql+jsp+servlet 模糊查询+删除+更新+分页+添加

文件介绍:

  1. com.lhy.bean Javabean
  2. com.lhy.dao
  3. com.lhy.servlet 

数据库的封装:这个部分我也是放在MovieDao.Java文件里面的,之后连接的话,直接调用就好啦~

    private PreparedStatement ps;//这个地方,你可以放在全局。之后做sql语句的预加载,就不用再创建咯
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/movies?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
			String username = "root";
			String password = "luo123456789";
			conn = DriverManager.getConnection(url, username, password);
		} 
		catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

模糊查询代码:

public ArrayList<Movie> FindMoviesByLikeName(String  name){
	ArrayList<Movie> list = new ArrayList<Movie>();
	try {
		Connection conn = MovieDao.getConnection();
		String sql = "SELECT * FROM  movie1 where name like ?";
		ps = conn.prepareStatement(sql);
		ps.setString(1, "%"+name+"%");
        ResultSet rs = ps.executeQuery();
       
		while (rs.next()) {
			Movie movie1 = new Movie(rs.getString("name") , rs.getString("director") ,
					rs.getString("tostar") , rs.getInt("score") , rs.getFloat("ticket"), rs.getString("film"));
			list.add(movie1);}
		    rs.close();
		    ps.close();
		    conn.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return list;
}

删除操作代码:

	public void  DeleteMoviesByName(String name) {
    	try {
			Connection conn = MovieDao.getConnection();
			String sql = "delete from movie1 where name=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.executeUpdate();
			ps.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		} }

更新操作代码:

  1. 对于这个更新操作,我是通过FindAllMovieServlet发送请求给我建立了一个的update.jsp更新界面,这个更新界面先进行回显
  2. 如何在设置一个按钮,修改完成之后,再返回到LookMovies.jsp。所以我们需要在MovieDao中写两个方法

     查询所有:作回显用

public ArrayList<Movie> findAll() {
		ArrayList<Movie> list = new ArrayList<Movie>();
		try {
			Connection conn = getConnection();
    			java.sql.Statement statement = conn.createStatement();
    			String sql = "SELECT * FROM movie1";
    			ResultSet rs = statement.executeQuery(sql);
    			
    			while (rs.next()) {
    			Movie movie = new Movie(rs.getString("name") , rs.getString("director") ,
    					rs.getString("tostar") , rs.getInt("score") , rs.getFloat("ticket"), rs.getString("film"));
    			list.add(movie);
    			}
    			rs.close();
    			statement.close();
    			conn.close();
    			} catch (SQLException e) {
    			e.printStackTrace();
    			}
    	return list;	
	}

    更新操作:

public void UpdateMovies(String name, String director, String tostar, int score, Float ticket, String film){
	try {
		Connection conn = MovieDao.getConnection();
		String sql = "Update movie1 set director=?, tostar=?, score=?, ticket=?, film=? where name=?";
		ps = conn.prepareStatement(sql);
		ps.setString(6,name);
		ps.setString(1,director);
		ps.setString(2,tostar);
		ps.setInt(3, score);
		ps.setFloat(4, ticket);
		ps.setString(5, film);
		ps.executeUpdate();
		ps.close();
		conn.close();
	} catch (Exception e) {
		e.printStackTrace();
	} 
}

  分页操作:

思维流程:

  1. 分页操作,我们肯定需要知道一共有多少数据吧,那么就需要建立一个方法去查询所有数据
  2. 如何你需要确定你想一页显示多少数据吧,我是用PAGE_SIZE变量储存
  3. 如何你有了总数和每一页的,是不是就可以去求一共有多少页?这个地方才是分页的关键之处,算法有很多,那么我是采用的最简单一种。欢迎补充!嘻嘻
  4. 有这么多数据,根据什么显示嘞?是不是要对数据的排序做一个规定。

第一步: 

	public int findCount() {
		int count = 0;
		Connection conn = getConnection();
		String sql = "select count(*) from movie1";
		try {
			java.sql.Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next()) {
				count = rs.getInt(1);
			}
			rs.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return count;
	}

第二步:

public List<Movie> find(int page) {
		List<Movie> list = new ArrayList<Movie>();
		Connection conn = getConnection();
		String sql = "select * from movie1 order by name desc limit ?,?";
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, (page - 1) * Movie.PAGE_SIZE);
			ps.setInt(2, Movie.PAGE_SIZE);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				Movie s = new Movie();
				s.setName(rs.getString("name"));
				s.setDirector(rs.getString("director"));
				s.setTostar(rs.getString("tostar"));
				s.setScore(rs.getInt("score"));
				s.setTicket(rs.getFloat("ticket"));
				s.setFilm(rs.getString("film"));
				list.add(s);
			}
			rs.close();
			ps.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

第三步:

package com.lhy.servlet;

import java.io.IOException;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lhy.bean.Movie;
import com.lhy.dao.MovieDao;

@WebServlet("/FindMovieBypageServlet")
public class FindMovieBypageServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int currPage = 1;
		if(request.getParameter("page")!=null) {
			currPage = Integer.parseInt(request.getParameter("page"));
		}
		MovieDao movieDao = new MovieDao();
		List<Movie>list = movieDao.find(currPage);
		request.setAttribute("list", list);
		int pages;
		int count = movieDao.findCount();
		if(count%Movie.PAGE_SIZE == 0) {
			pages = count/Movie.PAGE_SIZE;
		}else {
			pages = count/Movie.PAGE_SIZE+1;
		}
		StringBuffer sb = new StringBuffer();
		for(int i=1;i<=pages;i++) {
			if(i == currPage) {
				sb.append("["+i+"]");
			}else {
				sb.append("<a href='FindMovieBypageServlet?page="+i+"'>"+i+"</a>");
			}
			sb.append("  ");
		}
		request.setAttribute("bar", sb.toString());
		request.getRequestDispatcher("LookMovies.jsp").forward(request, response);
	}
}

添加操作:

public void AddMovies(String name, String director, String tostar, int score, Float ticket, String film) {
		try {
			Connection conn = MovieDao.getConnection();
			// 添加图书信息的SQL语句
			String sql1 = "INSERT INTO movie1 ( name, director, tostar, score, ticket, film )VALUES(?,?,?,?,?,?) ";
			// 获取PreparedStatement
			ps = conn.prepareStatement(sql1);
			ps.setString(1, name);
			ps.setString(2, director);
			ps.setString(3, tostar);
			ps.setInt(4, score);
			ps.setFloat(5, ticket);
			ps.setString(6, film);
			ps.executeUpdate();
			ps.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

部分界面展示:

                                                                  整体架构:

                                                                   主界面:

更新界面: 

  • 1
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
要实现搜索功能,需要以下步骤: 1. 创建一个包含搜索表单的 JSP 页面。该表单应该包含一个搜索框和一个提交按钮。 2. 创建一个 Servlet 来处理搜索请求。在 Servlet 中,你需要获取用户输入的搜索关键字,连接到数据库,并执行相应的搜索查询。 3. 在数据库中创建一个表来存储搜索数据。该表应该包含一个 id 列和一个 text 列。text 列是要被搜索的文本。 4. 在 Servlet 中使用 JDBC 连接到数据库。你需要执行一个 SELECT 查询来查找包含搜索关键字的行。你可以使用 PreparedStatement 来构建带有参数的 SQL 查询。 5. 将搜索结果返回到 JSP 页面。你可以使用 request.setAttribute() 方法来将搜索结果存储到 request 对象中,然后在 JSP 页面中使用 JSTL 标签来显示结果。 下面是一个简单的搜索示例,该示例使用 JSPServletMySQL 实现搜索: 1. 在 JSP 页面中添加以下搜索表单: ```html <form action="SearchServlet" method="GET"> <input type="text" name="keyword" placeholder="Enter a keyword"> <button type="submit">Search</button> </form> ``` 2. 创建一个 SearchServlet 类来处理搜索请求: ```java public class SearchServlet extends HttpServlet { private static final String DB_URL = "jdbc:mysql://localhost:3306/mydb"; private static final String DB_USER = "root"; private static final String DB_PASS = "password"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String keyword = request.getParameter("keyword"); try { // Connect to the database Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS); // Execute the search query PreparedStatement stmt = conn.prepareStatement("SELECT * FROM search_table WHERE text LIKE ?"); stmt.setString(1, "%" + keyword + "%"); ResultSet rs = stmt.executeQuery(); // Store the search results in the request object List<String> results = new ArrayList<String>(); while (rs.next()) { results.add(rs.getString("text")); } request.setAttribute("results", results); // Forward the request to the JSP page RequestDispatcher dispatcher = request.getRequestDispatcher("search-results.jsp"); dispatcher.forward(request, response); // Close the database connection conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 3. 在 MySQL 数据库中创建一个名为 search_table 的表: ```sql CREATE TABLE search_table ( id INT NOT NULL AUTO_INCREMENT, text TEXT, PRIMARY KEY (id) ); ``` 4. 创建一个名为 search-results.jspJSP 页面来显示搜索结果: ```html <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Search Results</title> </head> <body> <h1>Search Results</h1> <c:if test="${empty results}"> <p>No results found.</p> </c:if> <c:if test="${not empty results}"> <ul> <c:forEach var="result" items="${results}"> <li>${result}</li> </c:forEach> </ul> </c:if> </body> </html> ``` 这个示例演示了如何使用 JSPServletMySQL 实现搜索功能。你可以根据需要进行更改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不知名XL

你的鼓励是我的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值