两个java.sql.Date之间的Select语句

问题描述:

我的代码是:

    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;

我在使用Derby数据库,我必须运行此查询,但返回错误。我能怎么做?谢谢。

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

首先,停止构建这样的SQL 。它容易受到 SQL注入攻击,转换问题(这可能是这里的问题)并且很难阅读。

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.

改用参数化SQL:

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