gpt4 book ai didi

java - 从数据库获取最新数据到jsp页面

转载 作者:行者123 更新时间:2023-11-29 11:05:17 25 4
gpt4 key购买 nike

我正在尝试使用 servlet 和 jsp 从 mysql 数据库获取过去 5 天的数据。我创建了一个数据库类,它在其中查找最近 5 天到当前日期之间的日期。然后在我的 serlvet 上,我调用该方法并将值存储在列表中并将其转发到 jsp 页面。我在jsp页面中创建了一个表来显示数据库数据,但没有显示任何内容。我调试了它,它显示列表为空。我不确定我做错了什么。这是我的代码:

数据库方法:

public static List getMaxRecordsHomePage(int id) {
List recordList = new ArrayList<>();

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
String currentDate = dateFormat.format(date);

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -5);
Date previousDate = cal.getTime();
String fromDate = dateFormat.format(previousDate);

try {
Connection conn = DBConnection.getConnection();
String query = "SELECT * FROM record WHERE userId=? AND date BETWEEN ? AND ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setInt(1, id);
stmt.setString(2, fromDate);
stmt.setString(3, currentDate);
ResultSet rs = stmt.executeQuery();

while(rs.next()) {
Record records = new Record();
records.setId(id);
records.setCategory(rs.getString("category"));
records.setDescription(rs.getString("description"));
records.setAmount(rs.getString("amount"));
records.setDate(rs.getString("date"));
recordList.add(records);
}
} catch (Exception e) {
System.out.println(e);
}
return recordList;
}
}

服务器:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
int id = SessionService.getSessionId(request, response);
List recordList = FinanceService.getMaxRecordsHomePage(id);
request.setAttribute("recordList", recordList);

RouteService.routeDispatcher(request, response, "homepage.jsp");
}

JSP 页面:

<table>
<caption>Recent Records</caption>
<tr>
<td>Category</td>
<td>Short Description</td>
<td>Amount</td>
<td>Date</td>
</tr>
<c:forEach var="Records" items="${recordList}">
<tr>
<td><c:out value="${Records.category}"/></td>
<td><c:out value="${Records.description}"/></td>
<td>$<c:out value="${Records.amount}"/></td>
<td><c:out value="${Records.date}"/></td>
</tr>
</c:forEach>
</table>

最佳答案

The BETWEEN operator selects values within a range. The values can be numbers, text, or dates.

如果您想获取某个范围内的日期,您可以在数据库中选择“数据”、“日期时间”等列类型。

关于java - 从数据库获取最新数据到jsp页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41516207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com