Using Spring JdbcTemplate to extract one string

lkallas picture lkallas · Mar 26, 2015 · Viewed 64.8k times · Source

Can't seem to find a way to get one string from table using JdbcTemplate query. This is the table my sql returns:

ID | STREET_NAME
------------------------
1  | Elm street

Now how am I supposed to get the value of STREET_NAME. SQL always returns one row, so no need to worry about returning more than one row.

For some background info: INNER JOIN and COUNT in the same query

Using Tony Stark answer to get my table.

But how can I extract "Elm street" from it using JdbcTemplate?

Answer

jlewkovich picture jlewkovich · Mar 26, 2015

It would help a lot to know what your SQL query looks like, but assuming it's something like SELECT STREET_NAME FROM table WHERE ID=1;

CODE:

public String getStreetNameById(int id) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    String sql = "SELECT STREET_NAME FROM table WHERE ID=?";

    String streetName = (String) jdbcTemplate.queryForObject(
            sql, new Object[] { id }, String.class);

    return streetName;
}