Difference between DataSource and DriverManager

Difference between DataSource, Database and DriverManager

There are two sources of database connections - either a DataSource or a DriverManager.

If available, JNDI and the DataSource interface should be used to get a Connection instead of DriverManager. The JNDI style is typical when using an application server or a web container. (For example, the popular Tomcat product includes JNDI services and connection pools.)

Always remember that database connections need to be properly released!

Options for specifying the connection parameters include :

  • server configuration settings (likely the most common style)
  • direct user input for user name and password
  • a properties file, web.xml file, or ResourceBundle to keep parameters out of compiled code
  • the jdbc.drivers property of the System class

- no title specified

import java.sql.*;

import javax.naming.*;

import javax.sql.*;

final class GetConnection {

/** Uses JNDI and Datasource (preferred style). */

static Connection getJNDIConnection() {

String DATASOURCE_CONTEXT = "java:comp/env/jdbc/blah";

Connection result = null;

try {

Context initialContext = new InitialContext();

if (initialContext == null) {

log("JNDI problem. Cannot get InitialContext.");

}

DataSource datasource = (DataSource) initialContext

.lookup(DATASOURCE_CONTEXT);

if (datasource != null) {

result = datasource.getConnection();

} else {

log("Failed to lookup datasource.");

}

} catch (NamingException ex) {

log("Cannot get connection: " + ex);

} catch (SQLException ex) {

log("Cannot get connection: " + ex);

}

return result;

}

/** Uses DriverManager. */

static Connection getSimpleConnection() {

// See your driver documentation for the proper format of this string :

String DB_CONN_STRING = "jdbc:mysql://localhost:3306/airplanes";

// Provided by your driver documentation. In this case, a MySql driver

// is used :

String DRIVER_CLASS_NAME = "org.gjt.mm.mysql.Driver";

String USER_NAME = "juliex";

String PASSWORD = "ui893djf";

Connection result = null;

try {

Class.forName(DRIVER_CLASS_NAME).newInstance();

} catch (Exception ex) {

log("Check classpath. Cannot load db driver: " + DRIVER_CLASS_NAME);

}

try {

result = DriverManager.getConnection(DB_CONN_STRING, USER_NAME,

PASSWORD);

} catch (SQLException e) {

log("Driver loaded, but cannot connect to db: " + DB_CONN_STRING);

}

return result;

}

private static void log(Object aObject) {

System.out.println(aObject);

}

}



2 comments: