两个日期之间的SQL语句使用java字符串

时间:2015-04-03 12:50:41

标签: java sql between sql-date-functions

我正在尝试从表中收集数据,然后在两个日期语句之间运行。该语句在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 : "".

2 个答案:

答案 0 :(得分:3)

在SQL中,日期需要包含在引号'内,而不是主题标签#

更改后,此查询应该有效。

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# 

答案 1 :(得分: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)