The following example obtains an initial context before binding the UDBDataSource. The lookup method is then used on that context to return an object of type DataSource for the application to use.
// Import the required packages. There is no // driver-specific code needed in runtime // applications. import java.sql.*; import javax.sql.*; import javax.naming.*; public class UDBDataSourceUse { public static void main(java.lang.String[] args) throws Exception { // Retrieve a JNDI context. The context serves // as the root for where objects are bound or // found in JNDI. Context ctx = new InitialContext(); // Retrieve the bound UDBDataSource object using the // name with which it was previously bound. At runtime, // only the DataSource interface is used, so there // is no need to convert the object to the UDBDataSource // implementation class. (There is no need to know what // the implementation class is. The logical JNDI name is // only required). DataSource ds = (DataSource) ctx.lookup("SimpleDS"); // Once the DataSource is obtained, it can be used to establish // a connection. This Connection object is the same type // of object that is returned if the DriverManager approach // to establishing connection is used. Thus, so everything from // this point forward is exactly like any other JDBC // application. Connection connection = ds.getConnection(); // The connection can be used to create Statement objects and // update the database or process queries as follows. Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("select * from qsys2.sysprocs"); while (rs.next()) { System.out.println(rs.getString(1) + "." + rs.getString(2)); } // The connection is closed before the application ends. connection.close(); } }