0

I'm trying to get a SQL statement to select rows where a timestamp is between two given timestamps. here is what i tried. (this is on a Java servlet, and i java timestamp objects

SELECT * FROM dates WHERE dateAvailable >= " + from.toString() + " AND dateAvailable <= " + to.toString();

where from and to are timestamp objects this is giving me a syntax error when trying to prepare the statement, please help

kosa
  • 65,990
  • 13
  • 130
  • 167
Lor
  • 33
  • 3
  • 6
  • 2
    **Side note**: This way of making a query is _extremely vulnerable_ to SQL-Injections. Use [Prepared Statements](http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html) to add values to a query instead of just concatenating them in a string. – BackSlash Oct 10 '13 at 18:16

2 Answers2

4

JDBC has built-in types for this. Use

PreparedStatement ps = con.prepareStatement(
              "SELECT * FROM dates WHERE dateAvailable BETWEEN ? AND ?"); 
ps.setTimestamp(1, from);
ps.setTimestamp(2, to);

You specify two ? placeholder. You can set these to your TimeStamp elements.

Because it might not be immediately obvious, one purpose of using PreparedStatement is it helps prevent SQL injection. Read the answers here for more details.


The reason yours wasn't working is that Timestamp#toString() has a specific format that does not work with SQL.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
-1

You gotta use DATE functions otherwise you'll get strange side effects anyhow.

brez
  • 44
  • 3