Get database connection

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:

Example

Here's a reminder of the basics of getting a Connection.

import java.sql.*;
import javax.naming.*;
import javax.sql.*;

/** 
 Get a connection to a database.
 Callers need to close the connection when finished.  
*/
final class GetConnection {

  /** Preferred style, using JNDI and Datasource. */
  Connection getJNDIConnection(){
    String DATASOURCE_CONTEXT = "java:comp/env/jdbc/blah";
    Connection result = null;
    try {
      Context initialContext = new InitialContext();
      //cast is necessary
      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;
  }

  /** Using DriverManager, not JNDI. */
  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 = "bob";
    String PASSWORD = "cyclotronhydrantgracefulogre";
    
    Connection result = null;
    try {
      Class.forName(DRIVER_CLASS_NAME).getDeclaredConstructor().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 thing){
    System.out.println(thing);
  }
}
 

See Also :
Recovering resources
Connection pools