1 import java.sql.*; 2 import javax.naming.*; 3 import javax.sql.DataSource ; 4 5 9 public final class UseJndiDataSource 10 { 11 12 public static void main(String [] argv) 13 { 14 try 15 { 16 String jndiName = argv[0]; 19 20 InitialContext ctx = new InitialContext(); 27 28 DataSource ds = (DataSource ) ctx.lookup( jndiName ); 30 31 Connection con = null; 33 Statement stmt = null; 34 ResultSet rs = null; 35 try 36 { 37 con = ds.getConnection(); 38 stmt = con.createStatement(); 39 rs = stmt.executeQuery("SELECT * FROM foo"); 40 while (rs.next()) 41 System.out.println( rs.getString(1) ); 42 } 43 finally 44 { 45 attemptClose(rs); 52 attemptClose(stmt); 53 attemptClose(con); 54 } 55 } 56 catch (Exception e) 57 { e.printStackTrace(); } 58 } 59 60 static void attemptClose(ResultSet o) 61 { 62 try 63 { if (o != null) o.close();} 64 catch (Exception e) 65 { e.printStackTrace();} 66 } 67 68 static void attemptClose(Statement o) 69 { 70 try 71 { if (o != null) o.close();} 72 catch (Exception e) 73 { e.printStackTrace();} 74 } 75 76 static void attemptClose(Connection o) 77 { 78 try 79 { if (o != null) o.close();} 80 catch (Exception e) 81 { e.printStackTrace();} 82 } 83 84 private UseJndiDataSource() 85 {} 86 } 87 | Popular Tags |