如何在日期之间检索数据

时间:2016-03-26 18:48:26

标签: java mysql sql

我有2张桌子。预订桌和房间桌。在预订表中,我有以下列:BookingID StartDate EndDate CustomerID RoomID 在Room表格中,我有以下列:RoomID RoomSize

我正在创建一个预订系统。我希望能够在数据库中查询我能够获得在2个日期之间预订的房间列表,这些日期也基于大小(小,中或大)类型。

E.g。如果用户点击小房间并在2010-02-02至2010-02-25之间输入日期,则应显示4,因为我的数据库包含4个在这些日期之间预订的小房间。

这是我到目前为止所做的:

 String sqlStatement = "select RoomID from Booking where RoomID in (select Room.RoomID from Room where Room.RoomSize is " + type + ") AND ((Booking.StartDate between "+ startD +" AND " + endD + ") OR (Booking.EndDate between "+ startD + " AND " + endD + "))";

这是我得到的错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Medium) AND ((Booking.StartDate between 2016-02-09 AND 2016-02-09) OR (Booking.E' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)

我是SQL的新手并且在执行此操作时遇到了麻烦。还有,我的逻辑是对的吗? startDendD表示用户输入的日期,typeOfRoom表示用户想要预订的房间类型;例如eithier SmallMediumLarge

3 个答案:

答案 0 :(得分:1)

使用字符串连接将用户提供的值插入SQL,尤其是字符串。它会让您对SQL Injection攻击和SQL语法问题持开放态度。使用PreparedStatement

另外,将is替换为=

String sql = "select RoomID" +
              " from Booking" +
             " where RoomID in (" +
                       "select Room.RoomID" +
                        " from Room" +
                       " where Room.RoomSize = ?" +
                    ")" +
               " and ((Booking.StartDate between ? AND ?)" +
                 " or (Booking.EndDate between ? AND ?))";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setString(1, type);
    stmt.setDate  (2, startD);
    stmt.setDate  (3, endD);
    stmt.setDate  (4, startD);
    stmt.setDate  (5, endD);
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            // code here
        }
    }
}

答案 1 :(得分:0)

我认为日期处理看起来不错,但您需要在语句中引用type字符串。并且您不应该使用is,只需使用普通=

String sqlStatement = "select RoomID from Booking where RoomID in (select Room.RoomID from Room where Room.RoomSize = '" + type + "') AND ((Booking.StartDate between "+ startD +" AND " + endD + ") OR (Booking.EndDate between "+ startD + " AND " + endD + "))";

答案 2 :(得分:0)

如果此声明有效,您能试试吗?我已将'is'关键字替换为'='运算符,并将所有变量放在“”。

之间
String sqlStatement = "select RoomID from Booking where RoomID in (select Room.RoomID from Room where Room.RoomSize = \"" + type + "\") AND ((Booking.StartDate between \""+ startD +"\" AND \"" + endD + "\") OR (Booking.EndDate between \""+ startD + "\" AND \"" + endD + "\"))";