Reputation: 7435
I've been using PreparedStatements throughout my entire database where you can use setDate(index, data)
, however would it work to use a Date object like this?
"SELECT * FROM table WHERE date BETWEEN " + date + " AND " + otherDate
Are there any online tools that I can use to test this?
Upvotes: 0
Views: 530
Reputation: 16605
The best would be to format your date in a database recognizable format, when you append directly to the String
, the date's toString()
would be called, and I doubt that the database would support that syntax, you will be better off doing something like this:
final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = "SELECT * FROM table WHERE date BETWEEN '"
+ formatter.format(date) + "' AND " + formatter.format(otherDate) + "'";
Also, as kevin mentioned, rather stick to PreparedStatement
s, as this offers you more protection.
Upvotes: 1
Reputation: 94459
I do not believe this function will work:
"SELECT * FROM table WHERE date BETWEEN " + date + " AND " + otherDate
Since your trying to concatenate two Date
objects with several String
literals. You would need to use a DateFormatter
to turn the Date
into a String
.
You should stick with the PreparedStatement
s and avoid creating SQL statements by concatenating Strings/Values. The PreparedStatement
is going to offer you some protection against sql injection
, while the String concatenation method is going to expose you to the risk of sql injection.
Upvotes: 1