Using Spring JdbcTemplate to extract one string
If you want to get only one column "string" from your table (or any query with joins), you have to say the name of the column.
Using SELECT * FROM TABLE is a very-very bad practice by the way. I bet you did this.
@JLewkovich modified 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;
}
But what if there is 0 or more than one result? Think about it!
But to getting a sequence value (in Oracle), this should work.
public Long getSequence() {
Long seq;
String sql = "select SEQ_XY.NEXTVAL from dual";
seq = jdbcTemplateObject.queryForObject(sql, new Object[] {}, Long.class);
return seq;
}
The class JdbcTemplate
implements JdbcOperations
.
If you look at the queryForObject
javadocs in JdbcOperations
it states:
Deprecated. as of 5.3, in favor of queryForObject(String, Class, Object...)
Basically, they have changed the method signature to get rid of Object[]
arguments in the method signatures in favor of varargs. Please, see the relevant Github issue.
You can rewrite answer of @jlewkovich with the new method signature like this:
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, String.class, id);
return streetName;
}
As per latest specification queryForObject with below syntax is now deprecated
<T> T queryForObject(String sql, Object[] args, Class<T> requiredType)
New method uses varargs.
<T> T queryForObject(String sql, Class<T> requiredType, Object... args)
Updated Solution: We have to replace the class type with Object args and vice-versa.
Sql Query: SELECT STREET_NAME FROM table WHERE ID=1;
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, String.class, new Object[] { id });
return streetName;
}
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;
}