简体   繁体   中英

H2 org.h2.jdbc.JdbcSQLSyntaxErrorException when inserting a Timestamp

A SQL query comparing timestamps works in MySQL, but fails when using an H2 database.

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 .

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:

 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

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:

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.

The solution, thanks to @OleV.V's comment, was to pass the date objects in as an Object argument:

jdbcTemplate.query("SELECT * FROM table WHERE  time >= ? AND time <= ?", new Object[]{startTime, endTime}, (rs, i) -> Accessor.readFromResultSet(rs));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM