public ListRoom selectRoomString roomType String checkin ListRoom rooms = new ArrayList; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null;
/**
-
根据房间类型和入住时间查询房间列表
-
@param roomType 房间类型
-
@param checkin 入住时间
-
@return 房间列表 */ public List
selectRoom(String roomType, String checkin) { List rooms = new ArrayList<>(); // 创建一个房间列表 Connection conn = null; // 连接对象 PreparedStatement ps = null; // 预编译语句对象 ResultSet rs = null; // 结果集对象 try { conn = DBUtil.getConnection(); // 获取数据库连接 StringBuilder sql = new StringBuilder("SELECT * FROM room WHERE 1=1"); // 创建 SQL 语句 if (!roomType.isEmpty()) { // 如果房间类型不为空 sql.append(" AND roomType=?"); // 添加查询条件 } if (!checkin.isEmpty()) { // 如果入住时间不为空 sql.append(" AND checkin=?"); // 添加查询条件 } ps = conn.prepareStatement(sql.toString()); // 创建预编译语句对象 int index = 1; // 参数索引 if (!roomType.isEmpty()) { // 如果房间类型不为空 ps.setString(index++, roomType); // 设置查询参数 } if (!checkin.isEmpty()) { // 如果入住时间不为空 ps.setString(index++, checkin); // 设置查询参数 } rs = ps.executeQuery(); // 执行查询语句 while (rs.next()) { // 遍历结果集 Room room = new Room(); // 创建一个房间对象 room.setRoomId(rs.getInt("roomId")); // 设置房间编号 room.setRoomType(rs.getString("roomType")); // 设置房间类型 room.setCheckin(rs.getString("checkin")); // 设置入住时间 rooms.add(room); // 将房间对象添加到房间列表中 } } catch (SQLException e) { // 捕获 SQL 异常 e.printStackTrace(); // 输出异常信息 } finally { // 释放资源 DBUtil.closeAll(rs, ps, conn); // 关闭结果集、预编译语句和数据库连接 }
return rooms; // 返回房间列表
原文地址: http://www.cveoy.top/t/topic/dowe 著作权归作者所有。请勿转载和采集!