• Post Reply Bookmark Topic Watch Topic
  • New Topic

Best Way to Access Database from Servlet

 
Aryeh Golob
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had a question regarding best way to access database from a servlet.

Is it best to use a static method such as .....

or by using a local object ...It seems to me the pro's of using a static method is the ease of use. You can just get a database connection from anywhere w/o the hassle of instantiating a class.

The con, however, would seem to be the prevention of allowing anyone to get a database connection.

If someone could advise me regard the preferred method, I would certainly appreciate it.

Thanks in advance ....

-Aryeh
 
Hongli Li
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should abstract out your data access code to dao class or service class, you servlets should not contain any logic about dababase accessing.
 
Aryeh Golob
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Hongli and thanks for the response!

I am not sure that I am following and was wondering if you could explain in a bit more detail what you mean.

Thanks again for the help!

-Aryeh
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65524
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mixing database access code with UI interface code is an anti-pattern that Hongli is rightfully warning you against.

Segregate you data access into a model layer that is independent of the UI.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!