0

my code is:

    java.sql.Date fromDate= new java.sql.Date(date1);
    java.sql.Date toDate= new java.sql.Date(date2);

    String select = "SELECT * FROM Table WHERE Date between " + fromDate+ " and" + toDate;

I´m using Derby database, and I have to run this query but return error. How can I do? Thanks.

MartinGian
  • 395
  • 5
  • 16
  • 1
    "but return error" is *never* enough information. Please read http://tinyurl.com/so-hints before you ask your next question. – Jon Skeet Mar 10 '14 at 19:30
  • Sorry, is my first question. – MartinGian Mar 10 '14 at 20:00
  • The `java.util` Date-Time API is outdated and error-prone. It is recommended to stop using it completely and switch to the [modern Date-Time API](https://www.oracle.com/technical-resources/articles/java/jf14-Date-Time.html), released in March 2014. Check [this answer](https://stackoverflow.com/a/67505173/10819573) and [this answer](https://stackoverflow.com/a/67752047/10819573) which are based on the modern Date-Time API. – Arvind Kumar Avinash Jun 08 '21 at 19:37

2 Answers2

9

First, stop building SQL like that. It's vulnerable to SQL injection attacks, conversion issues (which is probably the problem here) and it's hard to read.

Use parameterized SQL instead:

// TODO: Close the statement, e.g. using a try-with-resources statement
// or a finally block.
PreparedStatement statement =
    conn.prepareStatement("SELECT * FROM Table WHERE Date between ? and ?");
statement.setDate(1, fromDate);
statement.setDate(2, toDate);
ResultSet results = statement.executeQuery();
// Use the results

This may well be enough to fix the problems immediately. If it's not, please give more details.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Use PreparedStatement. The JDBC tutorial includes plenty of examples.

While we are on the subject, this may be a good time to learn about SQL injection attacks (obligatory xkcd reference).

NPE
  • 486,780
  • 108
  • 951
  • 1,012