3

I have a standalone java application that gets streams of messages, batches and inserts them to a SQL Server database using Hikaricp.

Currently what I do is the following:

  • Get a connection from the pool.
  • Create a prepared statement to insert using the connection
  • Execute the batch insert.

Note that I never close the connection! And once I reach the maxPoolSize (20), I get an error when I tried to get a new connection.

Should I be closing the connection after every batch insert?

  • Get a connection from the pool.
  • Create a prepared statement to insert using the connection
  • Execute the batch insert.
  • Close the prepared statement & connection.

However, this means that I am incurring the cost of getting a connection from the pool + creating a new prepared statement after every batch insert.

Is this the recommended approach or are there any alternatives which can reduce this extra cost?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
CaptainHastings
  • 1,557
  • 1
  • 15
  • 32

1 Answers1

7

You need to close connection. usually pools return connections wrapped into another object. And when you call close on wrapper it simply marks internal database connection as free and returns it to the pool.

Also you can reuse existing PreparedStatement objects if they are the same. If each of your tasks has to use its unique PreparedStatement (due to your business logic) then there is no other way and you have to create new PreparedStatement for each task.

Ivan
  • 8,508
  • 2
  • 19
  • 30
  • Thank you Ivan. The query I execute in the PreparedStatement doesn't change. However, since it is associated with Connection (connection.prepareStatement(query), can I still reuse it if I close the connection it was used to create? – CaptainHastings Nov 02 '18 at 18:11
  • You need to close and recreate since `PreparedStatement` is linked to a `Connection` – Ivan Nov 02 '18 at 18:19