2014-01-08 33 views
3

我想使用不使用DriverManager的java數據源接口連接到Oracle數據庫。 我對此沒有想法。請爲我提供一個示例程序。使用DataSource接口連接Oracle數據庫的程序

+3

請通過下面的鏈接。它包含使用數據源信息進行連接所需的全部信息http://docs.oracle.com/javase/tutorial/jdbc/basics/sqldatasources.html – Jabir

+0

請點擊鏈接,這可能會對您有所幫助! [鏈接](http://docs.oracle.com/javase/tutorial/jdbc/basics/sqldatasources.html) –

回答

0

如果你想在這裏使用DataSource是要走的路:這是什麼roughtly下進行

// Setup the datasource 
DataSource ds = new OracleDataSource();// There is other DataSource offered by Oracle , check the javadoc for more information 
ds.setDriverType("thin"); 
ds.setServerName("myServer"); 
ds.setPortNumber(1521); 
ds.setDatabaseName("myDB"); 
ds.setUser("SCOTT"); 
ds.setPassword("TIGER"); 

// Get a JDBC connection 
Connection c = ds.getConnection(); 

封面。

但是,在現實生活中,你不會經常這樣做。假設您構建一個Web應用程序。通常,您將以文本格式配置數據源並將此配置放置在容器上。稍後,您可以通過JNDI檢索數據源(請參閱@Radhamani Muthusamy answer)。

+0

感謝您的回答..我現在就試試吧... – JavaFreak

+0

@AmrenduPandey別忘了添加用戶名和密碼(看我的更新) – Stephan

+0

是的,當然....我只是這樣做..謝謝... – JavaFreak

2

首先創建一個Datasource文件。數據源文件名可以在properties file給出。使用下面的代碼

ResourceBundle rb = ResourceBundle 
      .getBundle("com.cactus.xorail.properties.ConnectionProperties"); 
      InitialContext ic = new InitialContext(); 
      DataSource ds = (DataSource) ic.lookup("java:/" 
        + rb.getString("Datasource")); 
      if (ds == null) { 
       throw new SQLException(
         "Please configure datasource with name DS"); 
      }

 result = ds.getConnection(); 

0

//設置數據源對象

oracle.jdbc.pool.OracleDataSource ds 
    = new oracle.jdbc.pool.OracleDataSource(); 
    ds.setDriverType("thin"); 
    ds.setServerName("localhost"); 
    ds.setPortNumber(1521); 
    ds.setDatabaseName("XE"); // Oracle SID 
    ds.setUser("Herong"); 
    ds.setPassword("TopSecret"); 

//取得一個連接對象

con = ds.getConnection();