数据库名称:hotel 数据库表信息如下表:表名 room 实体名称 客房表主键 roomId序号 字段名称 字段说明 类型 位数 备注1 roomId 客房编号 int 主键自定义2 roomType 客房类型 nvarchar 5 非空值为单人间、标准间或豪华套房3 checkin 入住状态 nchar 1 非空值为是或否三、要求利用JDBC技术开发酒店客房管理系统中的客房查询模块用户
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 著作权归作者所有。请勿转载和采集!