我需要帮助在Java中的MySQL DateTime范围内进行选择

时间:2015-06-27 21:35:40

标签: java mysql datetime

我在我的应用中获得了以下代码

String sql = "SELECT colA, colB, colC " + 
    "FROM " + tblName + " WHERE UserId = " + userId + 
    " AND InsertTimestamp BETWEEN " + lastDate + 
    " AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
  if(null == conn)
    openDatabaseConnection();
  PreparedStatement stmt = conn.prepareStatement(sql);
  ResultSet rs = stmt.executeQuery();  <------- this is the line which throws the SQL exception
  retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
  JSONObject parms = new JSONObject();
  eh.processSQLException(methodName, sqle, sql, parms);
}

因此,当我在调试器中运行我的应用程序时,我收到此异常消息

  

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在00:00:00.0和2014-08-20 00:00:00.0之间使用正确的语法。按用户ID排序,发生&#39;在第1行

我合理地确定这是一个简单而合理的解决方案,但我一直无法找到它。

我已尝试在MySQL手册中查找解决方案或其他格式。

我尝试通过SQL中的TIMESTAMP()functino和DATE()函数运行我的时间戳,这两种方法都没有帮助。

我从Java代码中提取完全形成的SQL并在MySQL Workbench中运行它,没有任何问题,无论如何。所以现在我向专家寻求帮助。

1 个答案:

答案 0 :(得分:3)

SQL中的日期必须用单引号括起来,比如字符串。 当你使用准备好的状态时,为什么你不使用'?'和stmt.setDate(...)?

String sql = "SELECT colA, colB, colC " + 
"FROM " + tblName + " WHERE UserId = ?" + 
" AND InsertTimestamp BETWEEN ?" + 
" AND ? ORDER BY UserId, Occurred";
try {
    if(null == conn) {
        openDatabaseConnection();
    }
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setInt(1, userId);
    stmt.setDate(2, lastDate);
    stmt.setDate(3, DataProcessor.TODAY);
    ResultSet rs = stmt.executeQuery();  
    retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
    JSONObject parms = new JSONObject();
    eh.processSQLException(methodName, sqle, sql, parms);
}

无论如何,我认为你是按照相反的顺序设置日期。你应该把第一个'今天'然后放在lastDate。虽然我不知道你的约束......

相关问题