Java Database Connection

Usage of Relational Database is of vital to any enterprise software application even for a small device system. I found Java provided two method to achieve this goal. It provides the DriverManager object and the DataSource Object. However the recommendation is to use DataSource object.

The DriverManager class is the traditional management layer of JDBC, working between the user and the drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. In addition, the DriverManager class attends to things like driver login time limits and the printing of log and tracing messages. Two ways of establishing a connection is as follow :

  1. Class.forname(”my.db.Driver”);
  2. add the configuration to the java.lang.System :
    jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.test.ourDriver

Unlike the DriverManager, a DataSource object has properties that identify and describe the data source it represents. Also, a DataSource Naming and Directory Interface object works with a Java (JNDI) naming service and is created, deployed, and managed separately from the applications that use it. The advantages of DataSource over DriverManager are

  1. an application does not need to hardcode driver information, a programmer can choose a logical name for the data source and register the logical name with a JNDI naming service.
  2. the DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions.

Here is sample code to use DataSource:

//define your datasource
VendorDataSource vds = new VendorDataSource();vds.setServerName("my_database_server");
vds.setDatabaseName("my_database");
vds.setDescription("the data source for inventory and personnel");
Context ctx = new InitialContext();
ctx.bind("jdbc/AcmeDB", vds);
Connection con = ds.getConnection("genius", "abracadabra");
con.setAutoCommit(false);
//.....all your prepared statements....

 

Leave a Reply

You must be logged in to post a comment.