SQL语句语法错误

时间:2012-02-12 02:37:25

标签: java sql syntax

无法使用sql语句检索两个时间戳之间的记录。这只是给我一个NullPointerException,我认为它只是一个语法错误,我一直在搜索,我找不到任何东西。这是声明:

private static final String strGetRecordByDate =
    "SELECT * FROM APP.MYTABLE " +
    "WHERE MYDATE >= ?, AND MYDATE <= ? " +
    "VALUES (?, ?)";

创建声明:

stmtGetRecordByDate = dbConnection.prepareStatement(strGetRecordByDate);

null指针异常显示在stmtGetRecordByDate.clearParameters()上:

public Vector getRecordByDate(Date datefrom, Date dateto){
    Vector<String> records = new Vector<String>();
    ResultSet results = null;
    java.sql.Date sqlDatefrom = new java.sql.Date(datefrom.getTime());
    java.sql.Date sqlDateto = new java.sql.Date(dateto.getTime());
    try {           
        stmtGetRecordByDate.clearParameters();
        stmtGetRecordByDate.setDate(1, sqlDatefrom);
        stmtGetRecordByDate.setDate(2, sqlDateto);
        results = stmtGetRecordByDate.executeQuery();
        while (results.next()) {
            int id = results.getInt(1);
            String entry = results.getString(2);
            records.add(entry);
        }
    } catch(SQLException sqle) {
        sqle.printStackTrace();
    }
    return records;
}

其余的查询和语句工作正常,所以我知道数据库本身很好,但这个问题出了问题。

任何建议都会很棒。 谢谢!

1 个答案:

答案 0 :(得分:2)

您不能在该上下文中使用VALUES并且WHERE子句中有逗号逗号;你想要这个:

private static final String strGetRecordByDate =
        "SELECT * FROM APP.MYTABLE " +
        "WHERE MYDATE >= ? AND MYDATE <= ?";

您也可以使用BETWEEN

private static final String strGetRecordByDate =
        "SELECT * FROM APP.MYTABLE " +
        "WHERE MYDATE BETWEEN ? AND ?";

但这只是风格问题。

我不确定Java方面的情况,但由于您的SQL无效,您可能会在null中获得stmtGetRecordByDate