在数据库中建立表格T_BOOK(BOOKID,BOOKNAME,BOOKPRICE),插入一些记录。制作一个查询页面,输入两个数字,显示价格在这两个数字之间的图书信息。使用PreparedStatment命令执行sql,要求使用Java Bean技术的DAO和VO模式实现。
时间: 2024-02-06 10:08:54 浏览: 127
要求: 在数据库创建一个名为BookStore的数据库,在BookStore数据库中添加一个BookInfo表用于存储图书信息表
首先,我们需要创建一个Java Bean,来映射数据库中的T_BOOK表。假设我们的Java Bean叫做BookVO,代码如下:
```
public class BookVO {
private int bookid;
private String bookname;
private double bookprice;
public int getBookid() {
return bookid;
}
public void setBookid(int bookid) {
this.bookid = bookid;
}
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public double getBookprice() {
return bookprice;
}
public void setBookprice(double bookprice) {
this.bookprice = bookprice;
}
}
```
然后,我们需要创建一个DAO类,来操作T_BOOK表。假设我们的DAO类叫做BookDAO,代码如下:
```
public class BookDAO {
private Connection conn;
public BookDAO(Connection conn) {
this.conn = conn;
}
public List<BookVO> findByPrice(double minPrice, double maxPrice) throws SQLException {
List<BookVO> books = new ArrayList<>();
String sql = "SELECT BOOKID, BOOKNAME, BOOKPRICE FROM T_BOOK WHERE BOOKPRICE >= ? AND BOOKPRICE <= ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setDouble(1, minPrice);
stmt.setDouble(2, maxPrice);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
BookVO book = new BookVO();
book.setBookid(rs.getInt("BOOKID"));
book.setBookname(rs.getString("BOOKNAME"));
book.setBookprice(rs.getDouble("BOOKPRICE"));
books.add(book);
}
}
}
return books;
}
}
```
最后,我们可以在JSP页面中使用这个DAO类来查询数据库并显示结果。假设我们的JSP页面叫做query.jsp,代码如下:
```
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="com.example.BookDAO" %>
<%@ page import="com.example.BookVO" %>
<%
double minPrice = Double.parseDouble(request.getParameter("minPrice"));
double maxPrice = Double.parseDouble(request.getParameter("maxPrice"));
List<BookVO> books = null;
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password")) {
BookDAO dao = new BookDAO(conn);
books = dao.findByPrice(minPrice, maxPrice);
} catch (SQLException e) {
e.printStackTrace();
}
%>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
<% for (BookVO book : books) { %>
<tr>
<td><%= book.getBookid() %></td>
<td><%= book.getBookname() %></td>
<td><%= book.getBookprice() %></td>
</tr>
<% } %>
</table>
```
这个JSP页面会从请求参数中获取最小价格和最大价格,然后调用BookDAO中的findByPrice方法来查询数据库,并将结果显示在表格中。需要注意的是,这个JSP页面仅用于演示如何使用DAO和VO模式,实际应用中应该使用MVC或其他更合适的架构。
阅读全文