Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reusing Connection and Statement

 
Rajesh Pathak
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a application I have to query the same database many times (for select ,update...etc).
Should I reuse the same Connection and the same Statement? Or is it suggestable to follow the approach of create-use-close and so on.
Thanks in advance.
 
Andy Bowes
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The act of creating a new Connection to the database can take a significant length of time and so you would not want to do this every time that you execute a SQL statement. Ideally you should be using a pool of database connections that is managed by a javax.sql.DataSource resource. If you close a connection that is managed by the DataSource you are just returning it to the pool of available connections (i.e. it is not actually disconnected from the DB).
If you use the DataSource then you should get into the habit of writing getConnection() - use - close() code withing try {} catch() finally {} blocks to ensure that all of the DB resources are released even if an error occurs.
 
Andres Gonzalez
Ranch Hand
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might wanna check DBCOnnectionBroker, at www.javaexchange.com.

The Connection Broker completely avoids the overhead required in establishing a new database connection (typically around 1 to 2 seconds) by reusing a collection of pre-established connections

hope this helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic