在这种情况下,隔离应用程序的特定部分并使用小测试程序对其进行试验会非常有帮助。例如,我在 Access 中创建了一个 [Booking] 表...
BookingID RmID BookArrivalDate BookDepartureDate
--------- ---- --------------- -----------------
1 101 2013-10-21 2013-10-23
2 102 2013-11-01 2013-11-03
...然后使用以下小测试程序对其运行查询:
import java.sql.*;
import org.joda.time.*;
public class JDBCQuery {
public static void main(String args[]) {
Connection conn = null;
PreparedStatement s = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
"DBQ=C:\\Users\\Public\\Database1.accdb;");
LocalDate requestedArrivalDate = LocalDate.parse("2013-10-12");
LocalDate requestedDepartureDate = LocalDate.parse("2013-10-21");
s = conn.prepareStatement(
"SELECT BookingID, RmID FROM Booking WHERE BookDepartureDate > ? AND BookArrivalDate < ?");
s.setDate(1, new java.sql.Date(requestedArrivalDate.toDate().getTime()));
s.setDate(2, new java.sql.Date(requestedDepartureDate.toDate().getTime()));
ResultSet rs = s.executeQuery();
System.out.println(String.format("Requested arrival: %s", requestedArrivalDate.toString()));
System.out.println(String.format("Requested departure: %s", requestedDepartureDate.toString()));
System.out.println("The following bookings conflict with that request...");
if (rs!=null) {
while (rs.next()) {
System.out.println(String.format("BookingID: %d, RmId: %d", rs.getInt("BookingID"), rs.getInt("RmID")) );
}
}
System.out.println("(end of list)");
} catch( Exception e ) {
e.printStackTrace();
} finally {
try {
if (s != null) {
s.close();
}
if (conn != null) {
conn.close();
}
} catch( Exception e ) {
e.printStackTrace();
}
}
}
}
一旦我确信我的 SQL 逻辑是正确的并且能够隔离冲突的 Bookings(以及因此我无法使用的 RmID 值),那么很明显我希望我的最终查询看起来像这样:
SQL =
"SELECT RmID FROM Room " +
"WHERE " +
"RmID NOT IN " +
"(" +
"SELECT RmID FROM Booking " +
"WHERE BookDepartureDate > ? AND BookArrivalDate < ? " +
")" +
"AND RmType = ?";
s = conn.prepareStatement(SQL);
s.setDate(1, new java.sql.Date(requestedArrivalDate.toDate().getTime()));
s.setDate(2, new java.sql.Date(requestedDepartureDate.toDate().getTime()));
s.setString(3, "Single");
ResultSet rs = s.executeQuery();