File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

What's the best way to connect to DB

K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2380
    
    7

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?

Thanks


K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7 OCPWCD5
Paul Sturrock
Bartender

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.

http://www.hibernate.org/

c3p0:JDBC DataSources/Resource Pools
http://sourceforge.net/projects/c3p0
[ May 02, 2008: Message edited by: James Clark ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: What's the best way to connect to DB