0

我正在尝试从表中收集数据,然后运行两个日期之间的语句。该语句在 java 字符串中创建,然后由 resultSet 变量使用 statement.executeQuery() 以字符串作为参数。这就是我为两个日期创建字符串的方式:

Calendar today = Calendar.getInstance();
        int month = today.get(Calendar.MONTH);
        int year = today.get(Calendar.YEAR);
        int endOfMonth = today.getActualMaximum(Calendar.DATE);
        String sql;
        if (month < 10) {
            sql = "SELECT * FROM ORDERS WHERE DATE BETWEEN " + "#0" + month + "/01/" + year + "#" + " AND " + "#0" + month + "/" + endOfMonth + "/" + year + "#";

当我打印这个字符串时,结果是这样的:

SELECT * FROM ORDERS WHERE DATE BETWEEN #03/01/2015# AND #03/30/2015# 

但是,当我通过 executeQuery 方法运行此字符串时,会发生此错误:

java.sql.SQLSyntaxErrorException: Lexical error at line 1, column 41.  Encountered: "#" (35), after : "".
4

2 回答 2

3

在 SQL 中,日期需要包含在引号内,'而不是 hashtags内#

更改它们后,此查询应该可以工作。

SELECT * FROM ORDERS WHERE DATE BETWEEN '03/01/2015' AND '03/30/2015'

而不是

SELECT * FROM ORDERS WHERE DATE BETWEEN #03/01/2015# AND #03/30/2015# 
于 2015-04-03T12:56:11.087 回答
1

尝试这个:

  Calendar cal= Calendar.getInstance(); //Get the current date
  SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MMM/dd"); //format it as per your requirement
  String today = formatter.format(cal.getTime());
  String lastday = formatter.format(cal.getActualMaximum(Calendar.DATE));

  String sql;
  sql = "SELECT * FROM ORDERS WHERE DATE BETWEEN " + CONVERT(Char(10), today,112) + " AND " + CONVERT(Char(10), lastday ,112)
于 2015-04-07T05:34:20.090 回答