我是jsp的新手。这是我正在尝试做的:->从用户那里获取关键字输入(来自jsp表单)->从 postgres 关系数据库中的特定关系中搜索元组,该数据库包含任何列中的给定关键字。
我正在使用JDBC。我以为一切都很顺利,直到我发现一些具有给定关键字的元组没有显示。
关于数据库:数据库名称为"大学"。我的数据库"课程"中有一个关系,具有参数(course_id、标题、dept_name、学分)
以下是 jsp 页面的代码,我将在其中从用户那里获取输入关键字:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>search courses</title>
</head>
<body>
<h1>Search for courses</h1>
<FORM ACTION="coursesearch.jsp" METHOD="POST">
Type the keyword to search in course
<br> <input type="text" name="keyword" />
<br> <INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</body>
</html>
这是"课程搜索.jsp"的代码,它显示了课程中给定关键字的行:
<%@ page import="java.sql.*" %>
<% Class.forName("org.postgresql.Driver"); %>
<html>
<head>
<title>Question2</title>
</head>
<body>
<h1>Courses Containing the given keyword : </h1>
<%
Connection connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/university","postgres","password");
Statement statement1 = connection.createStatement();
String keyword = request.getParameter("keyword");
String sql = "select course_id,title from course where LOWER(title) LIKE LOWER(?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "%" + keyword + "%");
ResultSet resultset1 = preparedStatement.executeQuery();
if(!resultset1.next()){
out.println("Sorry no course found having given keyword");
}
else {
%>
<p>
Course IDs containing the given keyword
</p>
<table border="1">
<tr>
<th>Course ID</th>
<th>Course title </th>
<% while(resultset1.next()){ %>
<tr>
<td> <%=resultset1.getString(1)%> </td>
<td> <%=resultset1.getString(2)%> </td>
</tr>
<%
resultset1.next();
} %>
</table>
<br>
<% }
connection.close();
%>
</body>
</html>
对我来说一切看起来都很好,但该表并未显示所有有效的元组。说真的,我需要你们的帮助。(对不起,我的英语不好)。
您正在不知不觉中使用ResultSet
中的行。
这里:
if(!resultset1.next()){
//here you move from row 0 to row 1
然后在这里:
while(resultset1.next()){
最后,在这里:
resultset1.next();
基本上,您的代码如下所示:
if(!resultset1.next()) {
//advanced to the first row, but not consumed
while(resultset1.next()){
//advanced to the following row
//consumed this one...
resultset1.next();
//yet again advancing to the next row
//and not consuming it
}
}
相关:ResultSet.getString(1) 抛出 java.sql.SQLException:当前光标位置的无效操作
最后但并非最不重要的一点是,帮自己一个忙,避免使用脚本。
<%
try{
ResultSet rs = Database.getData("select * from event");
while(rs.next()){
%>
<tr>
<td><%= rs.getString("id") %></td>
<td><%= rs.getString("time") %></td>
<td><%= rs.getString("event") %></td>
<td><a href="#" class="btn btn-xs btn-warning"><span class="glyphicon glyphicon-trash"></span> Remove</a></td>
</tr>