File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes What's the best way to connect to DB Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What Watch "What New topic

What's the best way to connect to DB

K. Tsang

Joined: Sep 13, 2007
Posts: 3130

I'm doing a simple web project connecting to database. I have the data currently stored in some collections (eg arraylist hashmap etc) but want to insert that into db.

Do I use singleton, session bound, connect on demand, etc?


K. Tsang JavaRanch SCJP5 SCJD OCPJP7 OCPWCD5 OCPBCD5 OCPWSD5 OCMJEA5 part 1 part 2/3
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

Do I use singleton, session bound, connect on demand, etc?

Why use a singleton? What is it about your application that needs to ensure there is only one instance of a connection (or one instance of whatever object manages connections)?

session bound? I'm assuming by this you mean one connection per session? This kind of makes sense, except your database might provide far fewer connections than active sessions. Also is every session actively using the database? What about sessions that are currently unused and just waiting to time out?

connect on demand. By this I assume you mean every time a bit of your code needs a connection it just creates one? This is the most sensible approach - however, I'd suggest you look at using a connection pool. This way, from your coding point of view you just grab a connection when you need it, but your implementation handles the connections in a more prudent way.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
The "best" way to connect to a database is determined by the requirements and size of the application. Once you analyze these factors and a few others, you should be able to determine the "best" way for your application.

Take note, that this "best" way only applies to your application.

That said, I suggest that you review the Hibernate Framework. Using the Hibernate Framework to connect to a database is a very good strategy. It may work well for your application.

c3p0:JDBC DataSources/Resource Pools
[ May 02, 2008: Message edited by: James Clark ]
I agree. Here's the link:
subject: What's the best way to connect to DB
It's not a secret anymore!