参数化查询请求postgresql

Parametrized query request postgresql

我想从我的数据库中获取数据,其中 LocalDateTime 等于获取请求中的 LocalDateTime。

@Override
    public List<Timeslot> getAllAvailable(LocalDateTime localDateTime) {
        return jdbcTemplate.query("select * from timeslot where day = ?", TIMESLOT_ROW_MAPPER);
    }

时间段table代码:

CREATE TABLE "timeslot" (
    "timeslot_id" serial,
    "day" date NOT NULL,
    "start_time" TIME NOT NULL,
    "end_time" TIME NOT NULL,
    "user_id" serial NOT NULL,
    "is_recorded" boolean,
    CONSTRAINT "timeslot_pk" PRIMARY KEY ("timeslot_id")
);

控制器代码:

@GetMapping("/allAvailable")
    public List<Timeslot> getAllAvailable(@RequestParam("day") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime day) {
        return userService.allAvailable(day);
    }

但是当我在控制台中执行此请求时,结果是:org.postgresql.util.PSQLException: ERROR: syntax error at end of input。我如何更改 sql 请求代码以修复此错误?我应该使用 PrepareStatement 还是其他东西?

如@AndrewS 所述,您没有将 localDateTime 值作为参数传递。因此 jdbcTemplate 不会将 ? 绑定到 localDateTime。

您应该使用 query 的重载方法并将 localDateTime 作为最后一个参数传递:

jdbcTemplate.query("select * from timeslot where day = ?", TIMESLOT_ROW_MAPPER, localDateTime);

我认为您在数据库中将 存储为 Date 格式。在查询中,您正在比较类型为 DatedayLocalDateTime 类型,这可能是错误的。首先从 LocalDateTime 中获取 Date 然后作为方法参数传递。例如

jdbcTemplate.query("select * from timeslot where day = ?", TIMESLOT_ROW_MAPPER, localDateTime.toLocalDate());