包含Timestamp Date比较的SQL Query

时间:2016-02-18 08:32:28

标签: java sql

我有一个表 - event_log,其中有一个Timestamp格式的字段。一些示例条目是 - ' 2016-01-28 12:37:48' ,' 2016-01-28 15:26:51'

现在我想写一个查询,它将在startTime和endTime之间选择一些行。当我在SQL客户端

中触发此查询时
SELECT Time,Data
FROM event_log
WHERE Data IN ('player disconnected','Player connected to server')
    AND Player_Details_ID = '1'
    AND Time > '2016-01-28 11:46:49' AND Time < '2016-02-09 14:38:39'
ORDER BY Time;

它给了我想要的输出。但是当我用Java编写类似的查询时,它无法给我结果。

sqlQuery = "Select e.Time,e.Data"
                + " from event_log e "
                + "where e.Data IN ('player disconnected','Player connected to server') "
                + "and e.Player_Details_ID = '1' and "
                + "e.TIME > " + "' + startSqlDate + '" + " and e.TIME < " + "' + endSqlDate + '"                    
                + " order by e.Time";

我哪里错了?

4 个答案:

答案 0 :(得分:3)

无论任何&quot; startSqlDate&#39;的价值如何?和&#39; endSqlDate&#39;您可能已定义的变量,提交给数据库的查询将始终为:

Select e.Time,e.Data from event_log e where e.Data IN ('player disconnected','Player connected to server') and e.Player_Details_ID = '1' and e.TIME > ' + startSqlDate + ' and e.TIME < ' + endSqlDate + ' order by e.Time

这是因为您的变量名称在字符串中。将其更改为:

"Select e.Time,e.Data" + " from event_log e " + "where e.Data IN ('player disconnected','Player connected to server') " + "and e.Player_Details_ID = '1' and " + "e.TIME > '" + startSqlDate + "' and e.TIME < '" + endSqlDate + "' order by e.Time"

答案 1 :(得分:2)

你的第5行应该是:

+ "e.TIME > '" + startSqlDate + "' and e.TIME < '" + endSqlDate  + "'"

(如果您的变量是正确格式的字符串。)

您的版本根本不使用您的变量,而是编译为静态字符串。

答案 2 :(得分:2)

"e.TIME > " + "' + startSqlDate + '" + " and e.TIME < " + "' + endSqlDate + '"

而不是这个,请尝试以下

"e.TIME > '"+ startSqlDate + "' and e.TIME < '"+ endSqlDate + '"+ " order by e.Time";

答案 3 :(得分:0)

在我看来,你需要写\&#39;而不是&#39;。 这应该避免字符串的一些问题。 另外你可以看到你在字符串中有变量名。

这样的事情应该有效:

sqlQuery = "SELECT e.Time,e.Data"
            + " FROM event_log e "
            + "WHERE e.Data IN (\'player disconnected\',\'Player connected to server\') "
            + "AND e.Player_Details_ID = \'1\' AND "
            + "e.TIME > " + "\'" + startSqlDate + "\'" + " AND e.TIME < " + "\'" + endSqlDate + "\'"                    
            + " ORDER BY e.Time";