JNDI and the new JDBC 2.0 Standard Extension
import java.sql.*; import java.util.*; import javax.naming.*; import javax.sql.*; public class JNDIUser { public static void main(String args[]) { if( args.length > 0 && args[0].equals("install") ) { try { registerDataSource(); System.out.println("Data source 'jdbc/test' installed."); } catch( Exception e ) { e.printStackTrace(); System.out.println("Install failed."); } return; } try { Context ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup("/tmp/jdbc/test"); Connection con = ds.getConnection(); Statement stmt; ResultSet rs; stmt = con.createStatement(); rs = stmt.executeQuery("SELECT test_id, test_int, test_date, " + "test_char, test_val " + "FROM test ORDER BY test_id"); System.out.println("Got results:"); while( rs.next() ) { int i = rs.getInt(1); String s, comma = ""; java.util.Date d; System.out.print("\tkey: " + i + "("); i = rs.getInt(2); if( !rs.wasNull() ) { System.out.print("test_int=" + i); comma = ","; } d = rs.getDate(3); if( !rs.wasNull() ) { System.out.print(comma + "test_date=" + d); comma = ","; } s = rs.getString(4); if( !rs.wasNull() ) { System.out.print(comma + "test_char='" + s + "'"); comma = ","; } s = rs.getString(5); if( !rs.wasNull() ) { System.out.print(comma + "test_val='" + s + "'"); } System.out.println(")"); } con.close(); System.out.println("Done."); } catch( Exception e ) { e.printStackTrace(); } } static public void registerDataSource() throws Exception { com.imaginary.sql.msql.MsqlDataSource ds; Context ctx; ctx = new InitialContext(); ds = new com.imaginary.sql.msql.MsqlDataSource(); ds.setServerName("carthage.imaginary.com"); ds.setDatabaseName("test"); ctx.bind("/tmp/jdbc/test", ds); ctx.close(); } }
Page 2 of 2
This article was originally published on May 19, 1999