1 // ==================== Program Description ==========================
2 // 程序名称:示例13-5 : GetDataSource.java
3 // 程序目的:从命名服务中查询DataSource对象
4 // ==============================================================
5 import java.util.Hashtable ;
6 import javax.naming.* ;
7 import java.sql.* ;
8 import javax.sql.* ;
9
10 public class GetDataSource
11 {
12 public GetDataSource()
13 {
14 try {
15 // 建立JNDI上下文
16 Hashtable env = new Hashtable() ;
17 env.put(Context.INITIAL_CONTEXT_FACTORY,
18 "com.sun.jndi.fscontext.RefFSContextFactory") ;
19
20 Context ctx = new InitialContext(env) ;
21
22 // 查找对象
23 DataSource ds = (DataSource)ctx.lookup("jdbc/ datasource ") ;
24 // 获取数据库连接
25 Connection con = ds.getConnection() ;
26 con.close();
27 }
28 catch(Exception e ) {
29 e.printStackTrace();
30 }
31 }
32
33 public static void main (String args[]){
34 new GetDataSource() ;
35 }
36 }
|