[英]H2 org.h2.jdbc.JdbcSQLSyntaxErrorException when inserting a Timestamp
A SQL query comparing timestamps works in MySQL, but fails when using an H2 database. 比较时间戳的SQL查询在MySQL中有效,但在使用H2数据库时失败。
As an example, this is the query that produces the exception: 例如,这是产生异常的查询:
SELECT * FROM table WHERE time >= '2019-02-01T10:59:12.632Z' AND time <= '2019-04-12T10:59:12.632Z'
The query is created dynamically using Java code, and the timestamps above are of type java.time.Instant
. 该查询是使用Java代码动态创建的,并且上面的时间戳类型为java.time.Instant
。
I have even tried using other types of date/time objects, with the same outcome. 我什至尝试使用其他类型的日期/时间对象,但结果相同。
This query executes fine using MySQL, but throws the following error using an H2 DB: 使用MySQL可以很好地执行此查询,但是使用H2 DB会引发以下错误:
org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement
"SELECT * FROM table WHERE time>= 2019-04-10T13[*]:31:19.498Z AND time <= 2019-04-07T13:31:19.498Z";
SQL statement:
SELECT * FROM table WHERE time >= 2019-04-10T13:31:19.498Z AND time<= 2019-04-07T13:31:19.498Z
I find it puzzling that using colon-separated timestamps cause this issue, especially since the H2 docs use similar timestamps 我感到困惑的是,使用冒号分隔的时间戳会导致此问题,尤其是因为H2文档使用类似的时间戳
try converting date string properly 尝试正确转换日期字符串
SELECT * FROM table WHERE time >= str_to_date('2019-02-01 10:59:12.632 ', '%Y-%m-%d %T.%f')
AND time <= str_to_date( '2019-04-12 10:59:12.632 ' , '%Y-%m-%d %T.%f')
I am using Spring Boot's JdbcTemplate
and creating my queries as follows: 我正在使用Spring Boot的JdbcTemplate
并按如下方式创建查询:
jdbcTemplate.query("SELECT * FROM table WHERE time >= " + startTime + " AND " + " time <= " + endTime, (rs, i) -> Accessor.readFromResultSet(rs));
with the date Strings passed in as Instant
objects. 日期字符串作为Instant
对象传入。
The solution, thanks to @OleV.V's comment, was to pass the date objects in as an Object argument: 由于@ OleV.V的注释,解决方案是将date对象作为Object参数传递:
jdbcTemplate.query("SELECT * FROM table WHERE time >= ? AND time <= ?", new Object[]{startTime, endTime}, (rs, i) -> Accessor.readFromResultSet(rs));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.