92

I am reading the Java JDBC specification (vr. 4) and I encountred this statement:

DataSource — this interface was introduced in the JDBC 2.0 Optional Package API. It is preferred over DriverManager because it allows details about the underlying data source to be transparent to the application

What I am trying to understand is what the difference is between a Connection and a DataSource, and why it exists. I mean, the block above says that the details about a datasource is transparent to the application, but wouldn't externalizing database properties such as username, password, url etc in a property file and then use DriverManager work in the same way?

And is the DataSource interface created only to have a common way of returning connections that can be pooled etc? In Java EE, does the application server implement this interface and the applications deployed to have a reference to a datasource instead of a connection?

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
LuckyLuke
  • 42,935
  • 77
  • 254
  • 416

5 Answers5

73

Better scalability and maintenance

For DriverManager you need to know all the details (host, port, username, password, driver class) to connect to DB and to get connections. Externalizing those in a properties file doesn't change anything about the fact that you need to know them.

Using a DataSource you only need to know the JNDI name. The AppServer cares about the details and is not configured by the client application's vendor, but by an admin where the application is hosted.

Scalability:

Suppose you need to create connections yourself, how would you deal with changing load, sometime you have 10 users sometime you have 1000, you can't just get a connection whenever you need one and later 'release' it so the Database server does not get out of connections, which leads you to connection pooling. DriverManager does not provide it, DataSource does.

If you are going to program a connection pool yourself then you have to use DriverManager, otherwise go with DataSource.

Yousha Aleayoub
  • 3,221
  • 2
  • 42
  • 58
A4L
  • 16,713
  • 6
  • 43
  • 60
  • Now I understand it better. Who creates an implementation of a datasource? Is it the company like MySQL or is it for instance Glassfish? I guess it is the last since it is only a way to obtain a connection? Could you explain a litte more about that? – LuckyLuke Mar 04 '13 at 10:56
  • 4
    the Datasource implmentation is provided by the driver vendor (let's say MySQL). The appserver needs to know the driver to be able create the Datasource. After that it takes care of binding it to the JNDI name (logical name) that has been configured. Note that for this configuration step all the details (driver class, url, username, password etc.) have to be known. but this is still better than having these known by the client application. – A4L Mar 04 '13 at 14:05
  • What i cant explain is how an application server ca create a `DataSource` instance using a specific driver, all examples i could find must know the implementation of the `DataSource` interface so they can do something like `DataSource ds = new com.db.SomeDBVendorDatasource();`. I just cant belive that an application server does it this way :/ ... here some lecture i found: SQL Datasources http://docs.oracle.com/javase/tutorial/jdbc/basics/sqldatasources.html and Package javax.sql : http://docs.oracle.com/javase/6/docs/api/index.html?javax/sql/package-summary.html – A4L Mar 04 '13 at 14:06
  • @A4L: Can you please provide some small code snipt that clear's the DataSource usage.means How to use DataSource – kTiwari Sep 25 '13 at 09:21
  • @krishnaChandra, since you are asking about the usage, i guess you have already obtained a `DataSource`. What's left is just to retrieve connections from it see the javadoc for [javax.sql.DataSource](http://docs.oracle.com/javase/6/docs/api/javax/sql/DataSource.html) – A4L Sep 25 '13 at 09:35
  • 4
    `If you are going to program a connection pool then you have to use DriverManager, otherwise go with Datasource.` - did you flip the names? – arun Aug 07 '14 at 03:41
  • 3
    @arun I don't think so, DriverManager is a lower level API than DataSource. – A4L Aug 07 '14 at 06:54
  • 9
    @CodeChieftain I think he means, if you want to implement a Connection Pool yourself, so there is nothing to flip. – Koray Tugay Jul 29 '16 at 19:54
  • 1
    You know you do not have to use DataSource with JNDI. Also, if you wanted to, you might as well use DriverManager with JNDI as well. – Koray Tugay Sep 10 '16 at 11:43
  • 2
    Datasource provides connection polling. Last statement states if you wish to program connection polling go for DataManager. It can be bit misleading at first. It should be if you wish to have connection polling in your app go for datasource. – Aniket Thakur Feb 12 '17 at 19:16
  • @AniketThakur **1.** `DataManager` is not mentioned anywhere else other than in your comment on this page. **2.** `polling` and `pooling` are two different things. **3.** The last statement refers to **programming** a connection pool not **acquiring** connections. – A4L Dec 04 '17 at 11:59
39

DriverManager

  • hampers the application performance as the connections are created/closed in java classes.
  • does not support connection pooling.

DataSource

  • improves application performance as connections are not created/closed within a class, they are managed by the application server and can be fetched while at runtime.
  • it provides a facility creating a pool of connections
  • helpful for enterprise applications
Yousha Aleayoub
  • 3,221
  • 2
  • 42
  • 58
nav0611
  • 1,499
  • 14
  • 20
  • But if you created your own class such as MyConnectionPool and did some magic inside it with the DriverManager would that be the same as using a class that implements the DataSource interface? Is the DataSource interface only for having a common interface to get a connection? – LuckyLuke Mar 04 '13 at 09:52
  • 1
    Not exactly same.Framework like spring shows the capability of dataSource and its performance. – nav0611 Mar 04 '13 at 10:01
3

Below code shows two way for getting connection.

There is no need to know about URL in case of mySqlDataSource as this line is commented.

public class MySqlDataSourceTest {

public static void main(String[] args) throws SQLException, ClassNotFoundException {


    /************** using MysqlDataSource starts **************/
    MysqlDataSource d = new MysqlDataSource();
    d.setUser("root");
    d.setPassword("root");
//  d.setUrl("jdbc:mysql://localhost:3306/manavrachna");
    d.setDatabaseName("manavrachna");
    Connection c =  (Connection) d.getConnection();
    /************** using MysqlDataSource ends**************/


    /************** using DriverManager start **************/
    Class.forName("com.mysql.jdbc.Driver");
    Connection c=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/manavrachna","root","root");
    /************** using DriverManager ends **************/

    Statement st=(Statement) c.createStatement();
    ResultSet rs=st.executeQuery("select id from employee");
    while(rs.next())
    {
        System.out.println(rs.getInt(1));
    }

}

}
Thomas Rollet
  • 1,635
  • 3
  • 16
  • 28
Ram Tiwary
  • 39
  • 2
2

DataSource objects can provide connection pooling and distributed transactions, so you may have to use DataSource if you need one of or both these features.

Yousha Aleayoub
  • 3,221
  • 2
  • 42
  • 58
Koray Tugay
  • 20,438
  • 37
  • 155
  • 276
1

We can get connection using a datasource as follows. Use the connection to perform any database query.

DataSource datasource = (DataSource) new InitialContext().lookup(dataSourceName);
Connection connection = datasource.getConnection();
ansraju
  • 268
  • 2
  • 11