要实现查询票价区间最低价到最高价的功能,可以在查询语句中添加条件来筛选出符合条件的数据。以下是修改后的代码:

public List<Flight> charkFlight(String startCity, String endCity, String flightDate, int lowPrice, int highPrice) throws SQLException {

    List<Flight> lis = new ArrayList<>();

    //获取连接
    try {
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from flight where 1=1";
        if (startCity != null && !"".equals(startCity)) {
            sql += " and start_city = ?";
        }
        if (endCity != null && !"".equals(endCity)) {
            sql += " and end_city = ?";
        }
        if (flightDate != null && !"".equals(flightDate)) {
            sql += " and flight_date = ?";
        }
        if (lowPrice > 0 && highPrice > 0) {
            sql += " and ticket_price between ? and ?";
        }

        PreparedStatement ps = conn.prepareStatement(sql);
        int index = 1;
        if (startCity != null && !"".equals(startCity)) {
            ps.setString(index++, startCity);
        }
        if (endCity != null && !"".equals(endCity)) {
            ps.setString(index++, endCity);
        }
        if (flightDate != null && !"".equals(flightDate)) {
            ps.setString(index++, flightDate);
        }
        if (lowPrice > 0 && highPrice > 0) {
            ps.setInt(index++, lowPrice);
            ps.setInt(index, highPrice);
        }

        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Flight fi = new Flight();
            fi.setFid(rs.getInt("fid"));
            fi.setFlight_num(rs.getString("flight_num"));
            fi.setFlight_date(rs.getString("flight_date"));
            fi.setStart_city(rs.getString("start_city"));
            fi.setEnd_city(rs.getString("end_city"));
            fi.setStart_time(rs.getString("start_time"));
            fi.setEnd_time(rs.getString("end_time"));
            fi.setTicket_price(rs.getInt("ticket_price"));
            fi.setTicket_left(rs.getInt("ticket_left"));
            lis.add(fi);
        }

        return lis;

    } finally {
        try {
            JdbcUtil.freeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

在查询语句中添加了 ticket_price between ? and ? 条件来筛选出票价在指定区间的航班。同时,在预编译语句中设置了相应的参数

public ListFlight charkFlightString startCity String endCity String flightDate int lowprice int highPrice throws SQLException ListFlight lis = new ArrayList; 获取连接 try

原文地址: https://www.cveoy.top/t/topic/icIB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录