当我试图找到重叠时出错

时间:2013-12-06 18:48:48

标签: java mysql

当我试图找出计算机是否可用而不是出租给其他人时,我收到错误。我希望有人知道出了什么问题。

这是代码:

public boolean checkDate(int computerID, String from, String to) {

    String SQLString = "SELECT * FROM booking WHERE computerID= "+ computerID + " AND to > " + from + " AND from < " + to+ "";
    ResultSet rs;
    try {
        PreparedStatement query = DB.open().prepareStatement(SQLString);
        rs = query.executeQuery();
        rs.next();

        int rowCount = rs.getRow();

        if (rowCount < 1) {
            return true;
        }
    } catch (SQLException e) {
        System.out.println(e.toString());
    } finally {
        DB.close();
    }
    return false;

}

错误信息是:

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 ':00:56 AND start < 13:34:56' at line 1

已更新!

我现在已经更改了代码,因此它不会出错。但现在它总是回归真实:S

以下是更新后的代码:

public boolean checkDate(int computerID, String from, String to) {

    String SQLString = "SELECT * FROM booking WHERE computerID= "+ computerID + " AND slut > '" + from + "' AND start < '" + to+ "'";
    ResultSet rs;
    try {
        PreparedStatement query = DB.open().prepareStatement(SQLString);
        rs = query.executeQuery();
        rs.next();

        int rowCount = rs.getRow();

        if (rowCount < 1) {
            return true;
        }
    } catch (SQLException e) {
        System.out.println(e.toString());
    } finally {
        DB.close();
    }
    return false;

}

2 个答案:

答案 0 :(得分:0)

看起来fromto是时间戳。用单引号括起来应该解决这个问题。

此外,使用String来表示代码中的时间戳是糟糕的设计。

答案 1 :(得分:0)

如果数据库中与'from'和'to'对应的字段是datetime类型,则此查询将始终返回零或您的情况为true,因为从字符串到datetime的转换是非法的。尝试将“从”和“转换”转换为日期类型。请参阅示例click here