BadSqlGrammarException:PreparedStatementCallback;错误的SQL语法,当我给出时间戳参数时

时间:2019-09-25 07:53:02

标签: java sql jdbc

在我的Java应用程序中,我曾经有一个如下的sql查询:

INSERT INTO "KPI_MEASURE" (
        id,
        created_at,
        kpi_project_id,
        kpi_frequency_id,
        kpi_metric_id,
        branch,
        value
    )
SELECT
    nextval('"KPI_MEASURE_ID_seq"'::regclass),
    now(),
    kpi_measure.kpi_project_id,
    kpi_measure.kpi_frequency_id,
    kpi_measure.kpi_metric_id ,
    kpi_measure.branch ,
    sum(kpi_measure.value)
FROM "KPI_MEASURE" kpi_measure
    INNER JOIN "KPI_METRIC" kpi_metric                      ON kpi_measure.kpi_metric_id = kpi_metric.id
    INNER JOIN "KPI_PROJECT" kpi_project                    ON kpi_measure.kpi_project_id = kpi_project.id
    INNER JOIN "KPI_AGGREGATION_PROJECT" kpi_agg_project    ON kpi_project.name = kpi_agg_project.child_project_name
    WHERE kpi_metric.aggregated = false
GROUP BY kpi_measure.branch, kpi_measure.kpi_metric_id, kpi_measure.kpi_project_id, kpi_project.name, kpi_measure.kpi_frequency_id;

我使用jdbcTemplate.update执行了该sql,并且有效。
但是最近我通过一个参数now()更改了:today_date的值,我在代码中加上了该参数:

Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(TODAY_DATE, today); // TODAY_DATE = today_date

jdbcTemplate.update(sql, parameters);

但是现在,它会产生一个错误:

  

org.springframework.jdbc.BadSqlGrammarException:PreparedStatementCallback;错误的SQL语法   
...
嵌套异常是org.postgresql.util.PSQLException:未安装hstore扩展。

当我们想在jdbc查询中添加参数时,我不知道为什么会出错,因为这是我被告知要做的事情。


编辑:

列数据类型为timestamp without time zone,而today变量为String类型。
我想我应该使用Timestamp,所以我更改了代码:

Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(TODAY_DATE, new Timestamp(System.currentTimeMillis())); // TODAY_DATE = today_date

jdbcTemplate.update(sql, parameters);

现在我只有错误了

  

“ PSQLException:未安装hstore扩展。”

也许我需要添加一个hstore,但是我似乎不明白为什么。

1 个答案:

答案 0 :(得分:2)

您正在使用具有命名参数的JdbcTenmplate,但JdbcTemplate仅支持定位的参数(?)。将JdbcTemplate替换为NamedParameterJdbcTemplate或将查询重写为:

INSERT INTO "KPI_MEASURE" (
        id,
        created_at,
        kpi_project_id,
        kpi_frequency_id,
        kpi_metric_id,
        branch,
        value
    )
SELECT
    nextval('"KPI_MEASURE_ID_seq"'::regclass),
    ?,
    kpi_measure.kpi_project_id,
    kpi_measure.kpi_frequency_id,
    kpi_measure.kpi_metric_id ,
    kpi_measure.branch ,
    sum(kpi_measure.value)
FROM "KPI_MEASURE" kpi_measure
    INNER JOIN "KPI_METRIC" kpi_metric                      ON kpi_measure.kpi_metric_id = kpi_metric.id
    INNER JOIN "KPI_PROJECT" kpi_project                    ON kpi_measure.kpi_project_id = kpi_project.id
    INNER JOIN "KPI_AGGREGATION_PROJECT" kpi_agg_project    ON kpi_project.name = kpi_agg_project.child_project_name
    WHERE kpi_metric.aggregated = false
GROUP BY kpi_measure.branch, kpi_measure.kpi_metric_id, kpi_measure.kpi_project_id, kpi_project.name, kpi_measure.kpi_frequency_id;

并致电jdbcTemplate.update(sql, new Timestamp(System.currentTimeMillis()));