0
votes

I have a query which returns a single row with four integer columns.

select col1, col2, col3, col4 from myTable where id='xyz';

Which query method should I use from JdbcTemplate and how to put the values in four int variables say int1, int2, int3, int4 ?

The rowMapper answers given below will not work probably in my case. Because I do not have a object having four int properties, which I can set.

I am running a independent query in a method and I want to set the returned four column result to four integers which are local variables to that method.

I want to know, is this achievable through JdbcTemplate ???

Is below code valid?

List<String> result = this.jdbcTemplate.queryForObject(myQuery, List.class);

Iterator i = result.iterator();

String a = (String) i.next();
String b = (String) i.next();
String c = (String) i.next();
String d = (String) i.next();
2
Can you please put a appropriate reason for downvoting ? Just because its an easy question doesn't mean all will know!! If its a duplicate then please provide link to the other question. If not - then its a valid query. why downvote ? - Vicky
see my updated answer please. - flash

2 Answers

0
votes

You could use a queryForObject and map the rows to your object using a rowMapper. Check a sample here .

To map the result to local variables, use queryForList(String sql).See a sample here . You'll get a list of Object array from which you can extract values to your variables .

0
votes

Have you looked at the documentation?

There are some nice examples. Have a look at the query() method and the RowMapperclass.

Here is a simple Example:

//execute query
List<MyEntity> entityList = jdbcTemplate.query(myQuery, new MyRowMapper());

//myEntity is a representation of the rows in the table
    for (MyEntity myEntity : entityList) {
        int a = myEntity.getA();
        int b = ...
        //other getters
    }

class MyEntity {
    private int a;
    private int b;
    private int c;
    private int d;

    public void setA(int a) {
        this.a = a;
    }
    public int getA() {
        return a;
    }

    //other getters & setters
}

class MyRowMapper implements RowMapper<MyEntity> {

    @Override
    public MyEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
        MyEntity myEntity = new MyEntity();
        myEntity.setA(rs.getInt(0));
        myEntity.setB(rs.getInt(1));
        myEntity.setC(rs.getInt(2));
        myEntity.setD(rs.getInt(3));
        return myEntity;
    }
}