views:

455

answers:

4

Hi,

I have never connect a database in java before. May I know should I go about accessing a derby database with servlet?

I have checked out this: How do I access a database from my servlet or JSP? But I saw comments on the article saying that this is a bad way to connect. Could any one explain or show me the best way to that I should code to access my derby database?

Thank you very much.

+2  A: 

They are all right indeed, in suggesting that. We don't don't access database directly from Servlets or JSPs, these both are meant to be web tier, isn't it?

So, what to do? Grab a JDBC tutorial. The official one is an excellent choice here. That will give you a good idea about connecting to database from Java, and grasp over JDBC API. After that you should go and read about DAO pattern, and how we employ that in real apps.

Moreover, I think you also should read about MVC pattern, because it seems to me that you are not very clear on that as well.

Once you understand all these and come up with a toy like application using all these stuff. The step would be to have a look into Connection Pooling mechanism.

Adeel Ansari
+2  A: 

Since you are using servelt you must be using a container line Apache Tomcat. You should look to define a connection pool like this http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html. If you are using any other container then that will also have similar setup.

Other option is to create a separate DBManager kind of class which looks after initializing and returning connection. This class you can use in the servlet.

Bhushan
+1  A: 

Using JDBC and having your app server's application pool is a good start. You can also use some API to make your life easier like Hibernate.

mlaverd
+1  A: 

It is a "bad way", because it doesn't make use of a (JNDI-managed) connection pool to obtain connections. Although acquiring a connection costs "only" a few hundred milliseconds, this has impact in a busy multiuser environment. A connection pool will worry about opening and closing connections and release them immediately on every getConnection() call so that it effectively costs almost zero milliseconds. If you sum that up in a busy multiuser environment, then the differences are noticeable.

A connection pool is usually to be configured in flavor of a JNDI datasource which is managed by the servletcontainer in question. As you didn't mention which one you're using, I can at highest point to one of my answers which contains a Tomcat 6.0 targeted example: here.

Hope this helps.

BalusC