Java 在 H2 数据库中找不到函数“TO_DATE”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21544114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function "TO_DATE" not found in H2 database
提问by user3268428
I have a SQL statement and trying execute with H2 in-memory database in Java. The following exception thrown.
我有一个 SQL 语句并尝试在 Java 中使用 H2 内存数据库执行。抛出以下异常。
SQL:
查询语句:
SELECT ACCT_RULE_ID, ACCT_ACTION_ID
FROM ACCT_RULE
WHERE (ACCT_ACTION_ID = ?)
AND (START_DATETIME <= to_char(?, 'mm/dd/yyyy HH:MI:SS AM'))
AND (STOP_DATETIME > to_char(?, 'mm/dd/yyyy HH:MI:SS AM'))
Replacing first parameter with Id and second and third parameter with new Date() value.
用 Id 替换第一个参数,用新的 Date() 值替换第二个和第三个参数。
Exception:
Caused by: org.h2.jdbc.JdbcSQLException: Function "TO_DATE" not found; SQL statement:
回答by Tijo K Varghese
H2 database does not have TO_CHAR() function. But H2 database does have sysdate, dual, varchar2 which makes writing oracle query that will run on H2 database quite easy. So you can write a function instead which will H2 database function alias for making it handle date/timestamp with format. TO_CHAR(sysdate, 'DD/MM/YYYY HH24:MI:SS')
can be used in H2 database.
H2 数据库没有 TO_CHAR() 函数。但是 H2 数据库确实有 sysdate、dual、varchar2,这使得编写将在 H2 数据库上运行的 oracle 查询变得非常容易。因此,您可以编写一个函数来代替 H2 数据库函数别名,以使其处理带格式的日期/时间戳。TO_CHAR(sysdate, 'DD/MM/YYYY HH24:MI:SS')
可以在H2数据库中使用。
回答by Szabo Zoltan
H2 isn't support the to_date function yet.
H2 尚不支持 to_date 函数。
It's a priority 2 element in the roadmap
这是路线图中的优先级 2 元素
回答by David Small
One way to remove the time portion from a date-time field in H2, is to format the field as a string and then parse. This worked for me.
从 H2 中的日期时间字段中删除时间部分的一种方法是将该字段格式化为字符串,然后进行解析。这对我有用。
PARSEDATETIME(FORMATDATETIME(field_name, 'yyyy-MM-dd'), 'yyyy-MM-dd')
解析时间(格式化时间(字段名称,'yyyy-MM-dd'),'yyyy-MM-dd')
H2's parse and format date functions follow the java.text.SimpleDataFormat semantics.
H2 的解析和格式化日期函数遵循 java.text.SimpleDataFormat 语义。
Yes, it is NOT super optimized. This is fine for our needs since we only use H2 for unit tests.
是的,它不是超级优化的。这很好满足我们的需求,因为我们只使用 H2 进行单元测试。
回答by EoinS
you should be able to create your own to_date
function
您应该能够创建自己的to_date
功能
drop ALIAS if exists TO_DATE;
CREATE ALIAS TO_DATE as '
import java.text.*;
@CODE
java.util.Date toDate(String s, String dateFormat) throws Exception {
return new SimpleDateFormat(dateFormat).parse(s);
}
'
Of course you could also just use parsedatetime()
per David Small's answer
当然,您也可以parsedatetime()
按照 David Small 的回答使用