Ross
Ross

Reputation: 112

SQL statement syntax error

Having trouble with an sql statement to retrieve a record between two timestamps. This is just giving me a NullPointerException and I think it's just a syntax error, II've been searching around and I couldn't find anything. This is the statement:

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

creating the statement:

stmtGetRecordByDate = dbConnection.prepareStatement(strGetRecordByDate);

The nullpointer exception shows on 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;
}

The Rest of the queries and statements work fine so I know that the database itself is fine there is just something wrong with this one.

Any suggestions would be great. Thanks!

Upvotes: 0

Views: 258

Answers (1)

mu is too short
mu is too short

Reputation: 434595

You can't use a VALUES in that context and you have a stray comma in your WHERE clause; you want this:

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

You could also use BETWEEN:

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

but that's just a matter of style.

I'm not certain about the Java side of things but you're probably getting a null in stmtGetRecordByDate because of your invalid SQL.

Upvotes: 2

Related Questions