地铁查询系统阶段三 终于完成最短路径与换乘的查询
我通过B站找到了关于sql案例中的地铁查询系统案例,通过学习,以及自己的不断修改终于完成了查询的最后一个阶段。
以下是此次查询系统的核心代码:
chaxun-04.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<jsp:useBean id="dao" class="DAO.dao"></jsp:useBean>
<jsp:useBean id="dbutil" class="DBUTIL.dbutil"></jsp:useBean>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> 起点与终点途径站点</h1>
<body>
<body>
<table border="1" align="center">
<tr>
<th>1.经历站点个数</th>
<th>2.地铁站名</th>
</tr>
<%
//计算输入的起点与终点之间的站点数与换乘的最短路径
String station_name=request.getParameter("station_name");
String stop_station=request.getParameter("stop_station");
Connection connection = dbutil.getConnection();
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try{
String sql="WITH RECURSIVE transfer (start_station, stop_station, stops, path) AS (\r\n"
+ " SELECT station_name, next_station, 1, CAST(CONCAT(line_name,station_name , '->', line_name,next_station) AS CHAR(1000))\r\n"
+ " FROM bj_subway WHERE station_name = ?\r\n"
+ " UNION ALL\r\n"
+ " SELECT p.start_station, e.next_station, stops + 1, CONCAT(p.path, '->', e.line_name, e.next_station)\r\n"
+ " FROM transfer p\r\n"
+ " JOIN bj_subway e\r\n"
+ " ON p.stop_station = e.station_name AND (INSTR(p.path, e.next_station) = 0)\r\n"
+ ")\r\n"
+ "SELECT * FROM transfer WHERE stop_station =? limit 1 ";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1 ,station_name);
preparedStatement.setString(2 ,stop_station);
rs = preparedStatement.executeQuery();
while(rs.next()){
%>
<tr>
<td><%=rs.getString("stops") %></td>
<td><%=rs.getString("path") %></td>
</tr>
<%
}
}catch (Exception ex){
ex.printStackTrace();
}
finally{
dbutil.close(rs,preparedStatement,connection);
}
%>
</table>
</body>
</html>
查询案例图片:
以下是sql语句的中的表结构: