首先设计查询的页面:(如下图所示)
对应代码为:
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<head>
<title>提交页面</title>
</head>
<body>
请选择查询的条件<hr>
<form action="lianxi22.jsp" method="post">
性别:男<input type="radio" value="男" name="sex">
性别:女<input type="radio" value="女" name="sex"><br>
体重范围:<br>
最小:<input type="text" name="w1"><br>
最大:<input type="text" name="w2"><br>
<input type="submit" value="提 交">
<input type="reset" value="取 消">
</form>
</body>
</html>
再设计后台的处理页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<head>
<title>后台处理页面</title>
</head>
<body>
<%
// 先连接数据库
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/javaweb?useUnicode=true&characterEncoding=UTF-8";
String username="root";
String password="";
Connection conn= DriverManager.getConnection(url,username,password);
request.setCharacterEncoding("UTF-8");//设置字符编码,避免出现乱码
String sex = request.getParameter("sex");
float w1 = Float.parseFloat(request.getParameter("w1"));
float w2 = Float.parseFloat(request.getParameter("w2"));
String sql = "select * from student where sex=? and weight>=? and weight<=?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1,sex);
preparedStatement.setFloat(2,w1);
preparedStatement.setFloat(3,w2);
ResultSet resultSet = preparedStatement.executeQuery();//执行sql语句用来返回单个 ResultSet 对象
resultSet.last();//移动到最后一条记录
%>
<center>
你要查询的学生数据表中共有
<font size="5" color="red"><%=resultSet.getRow()%></font>人
<table border="2" bgcolor="ccceee" width="650">
<tr>
<td>记录条数</td>
<td>学号</td>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>体重</td>
<td>身高</td>
</tr>
<%
resultSet.beforeFirst();
while (resultSet.next()){
%> <tr align="center">
<td><%=resultSet.getRow()%></td>
<td><%=resultSet.getInt("id")%></td>
<td><%=resultSet.getString("name")%></td>
<td><%=resultSet.getString("sex")%></td>
<td><%=resultSet.getInt("age")%></td>
<td><%=resultSet.getInt("weight")%></td>
<td><%=resultSet.getInt("height")%></td>
</tr>
<%}%>
</table>
</center>
<%
if (resultSet!=null){
resultSet.close();
}
if (preparedStatement!=null){
preparedStatement.close();
}
if (conn!=null){
conn.close();
}
%>
</body>
</html>
输入对应的男女,再输入相应的体重,就能惊行查询,结果如下: