2013-06-20 71 views
0

我在研究IBM發佈的Managing database connections with JDBC。這是一些老東西(2001年)。他們正在使用JNDI。當我試圖執行其代碼:InitialContext工廠錯誤

try { 
     Hashtable env = new Hashtable(); 
     env.put(
     Context.INITIAL_CONTEXT_FACTORY, 
     "com.sun.jndi.fscontext.RefFSContextFactory"); 

     // Create the initial context 

     Context ctx = new InitialContext(env); 

     // Here we create the actual DataSource and then set the relevant 
     // parameters. 

     TdsDataSource ds = new TdsDataSource(); 

     ds.setServerName(serverName); 
     ds.setPortNumber(portNumber); 
     ds.setDatabaseName(databaseName); 
     ds.setUser(login); 
     ds.setPassword(password); 
     ds.setDescription("JDBC DataSource Connection"); 

     // Now we bind the DataSource object to the name we selected earlier. 

     ctx.bind(filePath, ds); 
     ctx.close(); 

    // Generic Exception handler, in practice, this would be replaced by an 
    // appropriate Exception handling hierarchy. 

    } catch (Exception ex) { 
     System.err.println("ERROR: " + ex.getMessage()); 
    } 

但是我發現沒有「com.sun.jndi.fscontext.RefFSContextFactory」文件系統服務提供商。然後我改變了代碼如下(從Initialize Data Source Properties)。

OracleDataSource ods = new OracleDataSource(); 
ods.setDriverType("oci"); 
ods.setServerName("dlsun999"); 
ods.setNetworkProtocol("tcp"); 
ods.setDatabaseName("816"); 
ods.setPortNumber(1521); 
ods.setUser("scott"); 
ods.setPassword("tiger"); 
Context ctx = new InitialContext(); 
ctx.bind("jdbc/sampledb", ods); 

當我試圖執行此代碼,我收到以下錯誤:

ERROR: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial 

我認爲它仍然要求的Context.INITIAL_CONTEXT_FACTORY。任何解決方案我從早上開始搜尋。

回答

0

這將是有益的,如果你可以發佈StactTrace或約容器/服務器的任何細節,你在運行此代碼。

DataSource對象和JNDI上下文是兩個不同的資源,但它們一起使用。 JNDI是一個存儲庫,可以保存由名稱等路徑標識的對象。 DataSource是一個包含使用JDBC建立數據庫連接的信息的對象。爲了提供對數據源的系統範圍訪問,它的對象將通過一個鍵綁定到JNDI,以便它可以在系統中全局查找。

似乎你的問題是與JNDI提供程序庫。您無需爲此更改DataSource實施庫(從TdsDataSourceOracleDataSource)。

可能是這個細節可以幫助你或發表更多的細節來了解你的運行時環境。

1

嘗試在創建InitialContext對象之前包含以下行。它應該解決問題。

System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory"); 
System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming"); 

這基本上告訴System其初始上下文庫您所使用的存儲您的數據源環境。

+0

這也行不通。這是說jdbc(在「jdbc/sampledb」)不在上下文中。 – kaushik