package com.mindprod.example;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* demonstrate the how to connect to a database via a DataSource.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2011-02-22 initial version
* @since 2011-02-22
*/
public class ConnectJDBCDataSource
{
/**
* which database
*/
private static final String DATA_BASE_NAME = "squirrels";
/**
* The connection. Handle to the database
*/
private static Connection conn;
/**
* connect to the database in the new "improved" way that requires five extra lines of meaningless bubblegum.
*/
private static Connection connect() throws NamingException, SQLException
{
System.setProperty( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
System.setProperty( Context.PROVIDER_URL, "file:///tmp" );
final Context initialContext = new InitialContext();
final Context envContext = ( Context ) initialContext.lookup( "java:comp/env" );
final DataSource ds = ( DataSource ) envContext.lookup( "jdbc/" + DATA_BASE_NAME );
return ds.getConnection();
}
/**
* initialise the database
*
* @param args not used
*/
public static void main( String[] args ) throws NamingException, SQLException
{
conn = connect();
conn.close();
}
}