简体   繁体   中英

Perform Update using Spring jdbctemplate

please suggest some way to perform the below query using jdbctemplate.

update student set result='pass' where stud_id in (100,101,102);

i have tried the below, but stuck with invalid column type.

i am passing the

String query = "UPDATE STUDENT SET RESULT = ? WHERE OBJ_ID IN ( SELECT * FROM TABLE )";
int[] stud_ids = new int[]{100,101,102};

  getJdbcTemplate().query(updateStateSQL, new PreparedStatementSetter() {

    @Override
    public void setValues(PreparedStatement ps) throws SQLException {
      final Connection con = getJdbcTemplate().getNativeJdbcExtractor().getNativeConnection(ps.getConnection());
      ps.setString(1, 'PASS');
      ps.setArray(2, stud_ids);
    }
  }, new RowMapper<String>() {

    @Override
    public String mapRow(ResultSet rs, int arg1) throws SQLException {
      return rs.getString(1);
    }
  });
}

You wrote:

String query = "UPDATE STUDENT SET RESULT = ? WHERE OBJ_ID IN ( SELECT * FROM TABLE )";

getJdbcTemplate().query(updateStateSQL, ...)

You didn't write the value of updateStateSQL . If it's the same as query , then this cannot work:

ps.setString(1, 'PASS');
ps.setArray(2, stud_ids);

Because you would need precisely 2 question marks ( ? ) in the query and you have only one in your post.

You could try this:

String query = "UPDATE STUDENT SET RESULT = ? WHERE OBJ_ID IN ( ? )";

But to be honest I've never used ps.setArray and I'm not sure it will do what you expect.

What should work is using NamedParameterJdbcTemplate , something like this:

String sql = "UPDATE STUDENT SET RESULT = :result WHERE OBJ_ID IN ( :ids )";
Map<String, Object> params = new HashMap<String, Object>();
params.put("result", "PASS");
params.put("ids", Arrays.asList(new Integer[] {100, 101, 102}));
getSimpleJdbcTemplate().update(sql, params);

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