• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initializing dB connection in init section

 
Suresh Kanagalingam
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I read lots of people saying that having dB connection initialized in 'init' section of a java code is not dependable, for the connection may be lost at any time. Instead suggested using a connection pool.
Can I implement a solution for this as outlined below:
1. create a connection in 'init' section.
2. Use this connection for rest of the requests until the connection is broken.
3. When a request is served I use "con.createStatement()" to get the result. During this time if I can not get the connection, then in 'catch' section I will create a new connection for the rest of the life of the servlet until the connection got broken again.
What is wrong doing this way? Can any one tell me if this will work or not?
Thanks in advance.
Suresh Kanagalinagm
 
Chantal Ackermann
Ranch Hand
Posts: 508
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
if you recreate the connection in the catch-clause this will work only after the statement has been requested. you would than have to reexecute the method that caused the exception. this is not an intuitive way to code.
the catch-clause is not the right place to do that, anyway. if you are expecting such an event (losing a connection), and that's a common event, than it's not an exception and therefor should not be handled in the catch-clause.
unfortunately, i don't know how to check if an connection is still sane. i'd like to know that myself!
what you could do is: check if the connection is broken (by creating the statement and checking, whether the statement is usable) and if so, create a new one. (the if-else-way) this piece of code should be placed in a method for its own (getConnection()).
chantal
 
Chantal Ackermann
Ranch Hand
Posts: 508
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry, i just read my own reply...
what i want to know is: is there another way to check the connection (if its broken or not) than to create a statement?
chantal
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic