-1

This are the code try with resources block.

try (Connection con = jdbcTemplate.getDataSource().getConnection();
                PreparedStatement preparedStatement = con.prepareStatement(sql);
                Statement statement = con.createStatement()) {
    
         ....
}
Rajat
  • 161
  • 1
  • 1
  • 5

2 Answers2

1

That code is wrong on more then one level. You have a JdbcTemplate and just use it as a carrier for the DataSource instead of using it properly.

Depending on what you want to do you should use one of the query or execute methods on the JdbcTemplate instead of obtaining the DataSource and getting the Connection.

If you really want the Connection use a ConnectionCallback with an execute method instead.

jdbcTemplate.execute( (Connection con) -> {
  PreparedStatement preparedStatement = con.prepareStatement(sql);
  Statement statement = con.createStatement();
})

But as mentioned you probably should be using one of the query methods instead of doing what youa re doing now!.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • I've upvoted this answer but wouldn't it be better to use: `jdbcTemplate.execute(sql, (PreparedStatement statement) -> { ... return null; });` – schwaller Jan 04 '23 at 17:23
  • It all depends on what you want to do, maybe you need the connection to prepare something before creating a statement. Ideally you would only need `jdbcTemplate.query*` methods and/or the basis `jdbcTemplate.update` but the need might arise one needs/want to use the plain `Connection`, `PreparedStatement` etc. Stating which one is better and should always be used isn't possible because it all depends. One thing can be said, `jdbcTemplate.getDataSource().getConnection()` is always a bad thing!. – M. Deinum Jan 04 '23 at 19:38
0

You could write it like this:

   DataSource ds = jdbcTemplate.getDataSource();
   if (ds != null) {
       try (Connection con = ds.getConnection();
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            Statement statement = con.createStatement()) {

            ....
       }
   }

The thing is that a DataSource is not AutoClosable. Therefore there is no need to manage it with the try with resources.

Furthermore, if the DataSource >is< null, you won't be able to get a connection or a statement, and there is probably nothing that you could sensibly in the try body if the statement was null. An explicit null test will avoid all of that.

But if we take into account the way that JdbcTemplate is designed to be used, I think that @M.Deinum's answer gives better ways to solve this.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • While it might be better to use some callback I don't think this is a real issue and could be considered false positive. – schwaller Jan 04 '23 at 17:13