//********************************************************************* // // Copyright (c) 2005-2008 by Teradata Corporation // All Rights Reserved // //********************************************************************* // // File: T21302JD.java // Purpose: Connect using a DataSource // //********************************************************************* import javax.naming.*; import java.sql.*; import javax.sql.*; import java.util.*; public class T21302JD { public static void main (String [] args) throws NamingException { try { // Set up the environment for creating the initial context Properties env = new Properties(); env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); env.setProperty(Context.PROVIDER_URL, "file:."); Context ctx = new InitialContext(env); System.out.println("Performing JNDI lookup for DataSource"); DataSource ds = (DataSource) ctx.lookup("TeraData1"); System.out.println("Requesting connection from DataSource"); Connection con1 = ds.getConnection(); System.out.println("Established successful connection using DataSource"); con1.close(); // The following code sample is for demonstration purposes only. // Sun's API documentation for the PooledConnection interface says: // "An application programmer does not use the PooledConnection interface // directly; rather, it is used by a middle tier infrastructure that // manages the pooling of connections." System.out.println("Performing JNDI lookup for ConnectionPoolDataSource"); ConnectionPoolDataSource cpds = (ConnectionPoolDataSource) ctx.lookup("TeraData2"); System.out.println( "Requesting PooledConnection from ConnectionPoolDataSource"); PooledConnection pcon = cpds.getPooledConnection(); try { System.out.println("Requesting connection from PooledConnection"); Connection con2 = pcon.getConnection(); System.out.println( "Established connection using ConnectionPoolDataSource"); con2.close(); } finally { pcon.close(); } System.out.println(" Sample T21302JD finished."); } catch (SQLException ex) { // A SQLException was generated. Catch it and display // the error information. // Note that there could be multiple error objects chained // together. System.out.println(); System.out.println("*** SQLException caught ***"); while (ex != null) { System.out.println(" Error code: " + ex.getErrorCode()); System.out.println(" SQL State: " + ex.getSQLState()); System.out.println(" Message: " + ex.getMessage()); ex.printStackTrace(); System.out.println(); ex = ex.getNextException(); } throw new IllegalStateException ("Sample failed.") ; } } }