2015-06-27 70 views
3

我有我的应用程序下面的代码我需要一个MySQL日期时间范围在Java中

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服务器版本对应的手册,以便在第1行'00:00:00.0和2014-08-20 00:00:00.0 ORDER BY UserId'发生时使用正确的语法。

I相当肯定的是,有一个简单而合理的解决方案,但我一直无法找到它。

我试过寻找解决方案或不同格式的MySQL手册。

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

我将完整的SQL从Java代码中提取出来并在MySQL Workbench中运行,没有任何问题。所以现在我正在寻求专家的帮助。

+0

http://bobby-tables.com/ –

+0

是的,我感觉你。这不是最好的编码实践,如果这不是一个私有方法从调用方法中传递给特定的,明确定义的parms,那么你就会死定了。 –

回答

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); 
} 

无论如何,我认为你是以相反顺序设置日期。你应该先把'今天'放到最后的日子。虽然我不知道你的约束...

+0

'stmt.setInteger(1,userId)'可能应该是'stmt.setString(1,userId)'(或'stmt.setInt(1,userId)')。 –

+0

是的,或setLong或其他,我不记得语法...改变了! –

+0

好吧,无论如何,你需要在单引号内包含日期,如果没有,你会得到'语法错误' –

相关问题