0

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?

0

2 Answers 2

1

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 PreparedStatements 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 PreparedStatements, as this offers you more protection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.