【问题标题】:Get PSQL Exception when passing List<String> as a Query parameter in "IN" clause using JDBCTemplate使用 JDBCTemplate 在“IN”子句中将 List<String> 作为查询参数传递时获取 PSQL 异常
【发布时间】:2019-11-15 18:09:37
【问题描述】:

我正在使用PostgreSQL 数据库创建Spring Boot 应用程序。我正在使用JDBCTemplate 来执行数据库操作。根据我的要求,我想要来自CONTRACT_VIEW_2 表的rowcount,其中LICENSE_PLATE = "xxxxxx"ZONE_CODE is IN ("x","y","z") 的值但我得到了PSQL 异常。

我尝试使用 MapSQLParameterSource,但仍然遇到问题。

@Override
public Integer getAllZoneForLp(String lp,List<String> zones) {
  MapSqlParameterSource zoneIds = new MapSqlParameterSource();
  zoneIds.addValue("zoneIds",zones);
  String sql = "select " +
        "count(*) " +
        "from contract_view_2 " +
        "where license_plate = ? and zone_code IN (?)";
  return jdbcTemplate.queryForObject(sql,Integer.class,lp,zoneIds);
}

我希望结果中出现row count,但我得到的是PSQL Exception。我附上了我得到的异常的图像。

提前致谢。

【问题讨论】:

    标签: java postgresql spring-boot jdbctemplate


    【解决方案1】:

    您的问题是您已将Namedparameter 添加到JdbcTemplate

    所以如果你使用NamedParameterJdbcTemplate

    @Override
    public Integer getAllZoneForLp(String lp,List<String> zones) {
      MapSqlParameterSource parameters = new MapSqlParameterSource();
      parameters.addValue("lp", lp);
      parameters.addValue("zoneIds",zones);
      String sql = "select " +
            "count(*) " +
            "from contract_view_2 " +
            "where license_plate = :lp and zone_code IN (:zoneIds)";
      NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
    
      return namedParameterJdbcTemplate.queryForObject(sql, parameters, Integer.class);
    }
    

    如果你想使用jdbcTemplate

    @Override
    public Integer getAllZoneForLp(String lp,List<String> zones) {
      String sql = "select " +
            "count(*) " +
            "from contract_view_2 " +
            "where license_plate = ? and zone_code IN (?)";
    
      return jdbcTemplate.queryForObject(sql, Integer.class, new Object[] { lp, zones}); 
    }
    

    使用NameParameterJdbcTemplate,这样您就不会错过任何参数。

    【讨论】:

      【解决方案2】:

      请将您的查询更改为

        String sql = "select " +
              "count(*) " +
              "from contract_view_2 " +
              "where license_plate = ? and zone_code IN (:zoneIds)";
      

      变化:改变了?到 :zoneIds

      zoneIds.addValue("zoneIds",zones); 行正在使用命名参数绑定它。

      【讨论】:

        猜你喜欢
        • 2016-09-27
        • 2018-06-18
        • 1970-01-01
        • 2012-11-01
        • 1970-01-01
        • 2015-11-20
        • 2021-12-25
        • 2019-08-05
        • 1970-01-01
        相关资源
        最近更新 更多