RoomDao类代码如下:

import java.sql.*; import java.util.ArrayList; import java.util.List;

public class RoomDao { private final String URL = "jdbc:mysql://localhost:3306/hotel"; private final String USERNAME = "root"; private final String PASSWORD = "password";

public List<Room> selectRoom(String roomType, String checkin) {
    List<Room> roomList = new ArrayList<>();
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

        // 构造查询语句
        String sql = "SELECT * FROM room WHERE 1=1";
        if (!roomType.equals("")) {
            sql += " AND roomType=?";
        }
        if (!checkin.equals("")) {
            sql += " AND checkin=?";
        }
        pstmt = conn.prepareStatement(sql);
        int index = 1;
        if (!roomType.equals("")) {
            pstmt.setString(index++, roomType);
        }
        if (!checkin.equals("")) {
            pstmt.setString(index++, checkin);
        }

        // 执行查询语句
        rs = pstmt.executeQuery();
        while (rs.next()) {
            Room room = new Room();
            room.setRoomId(rs.getInt("roomId"));
            room.setRoomType(rs.getString("roomType"));
            room.setCheckin(rs.getString("checkin"));
            roomList.add(room);
        }
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return roomList;
}

}

其中,Room类为客房实体类,包含roomId、roomType和checkin三个属性的get/set方法


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

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