Wednesday, August 12, 2009

How do I connect to a database from my Servlet?

Java includes support for databases, using Java Database Connectivity (JDBC). Most modern databases offer JDBC drivers, which allow you to connect any Java application (including Servlets) directly to your database.
If your database vendor does not offer a JDBC driver, and there are no third party drivers available, you may like to use a JDBC bridge. For example, the ODBC-JDBC bridge allows you to connect to any ODBC data source, which many databases support. Also there are four type of Drivers

Type I : JDBC-ODBC bridge
Type II : native-API partly JavaTM technology-enabled driver
Type III : net-protocol fully Java technology-enabled driver
Type IV : native-protocol fully Java technology-enabled driver
For a list of currently available Database drivers, please visit this page http://industry.java.sun.com/products/jdbc/drivers

Creating a new Connection to Database frequently could slow down your application. Most of the projects use a concept called Connection Pooling. Here when the Servlet starts up, in the init method , a pool of connections are created and are stored in memory (Mostly in a Vector). When a transaction with Database is required, then the next free available connection is retrieved from this Vector and used for that purpose. Once it's work is done, it is again put back into Connections Pool, indicating it is available. Today most of the JDBC Drivers support this feature have inbuilt connection pooling mechanisms.

Please Note : If you are creating your own Connection Pooling, it is strongly recommended to close all the open connections in the destroy method. Else there are chances of your data getting corrupted.

No comments:

Post a Comment