SQL 在两个日期语句之间使用 java 字符串
SQL between two dates statement using java string
我正在尝试从 table 和 运行 两个日期之间的语句中收集数据。该语句在 java 字符串中创建,然后由结果集变量使用 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 : "".
在 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#
试试这个:
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)
我正在尝试从 table 和 运行 两个日期之间的语句中收集数据。该语句在 java 字符串中创建,然后由结果集变量使用 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 : "".
在 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#
试试这个:
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)