简体   繁体   中英

jdbctemplate - queryForList - Passing a date?

I'm writing a small spring application which has jdbc functionality in the context of the following code...

I have the following java to set up an SQL query string:

    String sql =
            "SELECT " +
                    "    a.Id, " +
                    "    a.USER_ID ", " +
                    "    a.LAST_UPDATED " +
                    "from " +
                    "    Schema.AwesomeTable a " +
                    "where " +
                    "    a.LAST_UPDATED >= ?";

and I am trying to use a date object (let's just imagine I am using the current date for the sake of this question remaining brief):

Date myDate = new Date(); // This is a java.util.Date

and I am calling the query like this:

List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, new Object[]{myDate});

When I run this - I get this error:

2019-04-08 23:17:58 - Setting SQL statement parameter value: column index 1, parameter value [Tue Apr 08 23:17:58 CDT 2019], value class [java.util.Date], SQL type unknown

I could really use some help - I have googled around everywhere, and I've found SOME information, but I haven't seen anything that I seem to be able to grasp.

You could wrap your parameter in java.sql.Date or use:

import java.util.Date;
import java.time.LocalDate;

LocalDate dateTime = // some date here
Date startDate = Date.from(dateTime.atStartOfDay(ZoneId.systemDefault()).toInstant());

You can't directly use myDate variable of type java.util.Date in your sql query

Date myDate = new Date(); // This is a java.util.Date

you have to convert it to java.sql.Date type which you can do as follows:

java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());

after which you can call the query like:

List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql,sqlDate);

which will work as expected.

**LocalDate can be pass as String in prepard statement directly **

jdbcTemplate.query(selectSqlQuery,
                    ps -> {
                        ps.setString(1, searchDate.toString());
                    }, new RowMapperForOutput());

Query:

select * from table1 where date(date_column)=?;

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