我必须检查特定时段内的可用房间,即从酒店预订系统的开始日期到结束日期。为了选择开始和结束日期,我使用了JCalendar。问题是我在创建SQL字符串查询时遇到错误,而且我也不知道如何从JCalendar中检索要在查询中使用的日期。
以下是我所做的以及我被困的地方的代码片段。
JCalendar实例化:
JDateChooser arrival = new JDateChooser();
JDateChooser departure = new JDateChooser();
查询可用房间:
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
try {
// new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/testing?autoReconnect=true&useSSL=false";
String connectionUser = "root";
String connectionPassword = "admin";
conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
stmt = conn.createStatement();
String query = "select * from testing.room as ro
where ro.room_id not in
(
select re.room_no
from testing.booking as re
where (arrival_date >= "2016-05-24" and departure_date < "2016-05-29")
or (departure_date >= "2016-05-24" and arrival_date < "2016-05-29")
)";
rs = (ResultSet) stmt.executeQuery("");
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getString(2)
+ " " + rs.getString(3)+ " " + rs.getString(4)+ " "+ rs.getString(5));
}
} catch (Exception e) {
e.printStackTrace();
}
我在这里硬编了日期:
where (arrival_date >= "2016-05-24" and departure_date < "2016-05-29")
or (departure_date >= "2016-05-24" and arrival_date < "2016-05-29")
那是因为我不知道如何从JCalendar中取出值来编写它,即我应该使用PreparedStatements获取文本还是什么?
而且,我收到了查询错误,即我在哪里写了字符串查询=&#34;查询&#34;正如它所说&#34;插入缺失的引号&#34;。
答案 0 :(得分:1)
您需要在此处进行两项更改:
JDateChooser
字段中获取日期(在getDate()
个对象上调用JDateChooser
方法)。使用PreparedStatement
并动态设置日期。以下是一个例子:
JDateChooser arrival = new JDateChooser();
JDateChooser departure = new JDateChooser();
PreparedStatement pStmt = conn.prepareStatement("select * from testing.room where arrival_date >= ? and departure_date < ?");
pStmt.setDate(1, arrival.getDate());
pStmt.setDate(2, departure.getDate());
ResultSet rs = preparedStatement.executeQuery();