0

I tried to share a Jdbc Connection object in the ServletContext, but it's not a good idea! Now i think to share a Jdbc for each Servlet! in manner that all and only the same Servlet's threads share the connection. Now i've some doubts! Is it an error or is it not enough safe? Finally i use MySql, are there some problem with the connection's timeout property? Thanks all.

paolo2988
  • 857
  • 3
  • 15
  • 31
  • `I tried to share a Jdbc Connection object in the ServletContext, but it's not a good idea!` Why it is not a good idea? – Paulius Matulionis Oct 25 '12 at 10:07
  • @Paulius: for reasons mentioned in [this answer](http://stackoverflow.com/questions/9428573/is-it-safe-to-use-a-static-connection-java-sql-object-in-a-multithreaded-syste/9431863#9431863). – BalusC Oct 25 '12 at 12:40
  • Because i didn't know about existence of connection pooling and i was trying to make this using a class write by me. – paolo2988 Oct 25 '12 at 13:23

1 Answers1

0

You need connection pooling. It is a standard way of doing this. Please go read about connection pooling and how to implement it in Java.

You can read this answer to explain it a little more: Opening a database connection in a constructor, when should I close it?

Community
  • 1
  • 1
Namphibian
  • 12,046
  • 7
  • 46
  • 76
  • If I understand correctly i have to edit the "context.xml" and after create the pool in the init() method. But one thing it's not clear, if i create the pool in every Serlvet Init(), will i get a distinct pool for each Servlet? Otherwise if i do that in ServletContextListener will i get a pool shared by all Servlets? – paolo2988 Oct 25 '12 at 15:57
  • What server are you using for servlet deployment? Sounds like you are using TomCat? Please let me know so I can answer some specific questions around this. – Namphibian Oct 28 '12 at 05:57
  • Yes, i'm using TomCat 7 and i'm developing my web application using NetBeans. So, when i try a new Servlet or a new functionality in local i use TomCat within NetBeans. Thanks for your help. – paolo2988 Oct 28 '12 at 10:21