I want to know what is the best practice to select records from a table. I mentioned two methods below from that I want to know which one is best practice to select the data from a table using Spring JdbcTemplate.
First example
try {
String sql = "SELECT id FROM tableName WHERE column_name = '" + coulmn value + "'";
long id = jdbcTemplate.queryForObject(sql, Long.class);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(e);
}
}
This throws the following exception:
Expected 1 actual 0 like
when table doesn't contain any data. My friend told this is not the best practice to select the data. He suggested that the below mentioned code is the only best practice to select data.
Second example
try {
String countQuery = "SELECT COUNT(id) FROM tableName";
int count = jdbcTemplate.queryForInt(countQuery);
if (count > 0) {
String sql = "SELECT id FROM tableName WHERE column_name = '" + coulmn value + "'";
long id = jdbcTemplate.queryForObject(sql, Long.class);
}
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(e);
}
}
I'm eager to know the right one or any other best practice.